Tidy long string in Ruby
我有一个Ruby方法,它需要一个API URL:
1 | request_url ="http://api.abc.com/v3/avail?rev=#{ENV['REV']}&key=#{ENV['KEY']}&locale=en_US¤cyCode=#{currency}&arrivalDate=#{check_in}&departureDate=#{check_out}&includeDetails=true&includeRoomImages=true&room1=#{total_guests}" |
我想把它格式化为更可读的格式。它应该有论点。
1 2 3 4 5 6 7 8 9 10 | request_url ="http://api.abc.com/v3/avail? &rev=#{ENV['REV']} &key=#{ENV['KEY']} &locale=en_US ¤cyCode=#{currency} &arrivalDate=#{check_in} &departureDate=#{check_out} &includeDetails=true &includeRoomImages=true &room1=#{total_guests}" |
号
但当然有断线。我在这里试过了,医生,但我希望它在一条线上。
我宁愿不通过连接字符串来构建URI查询,因为这可能导致URL编码不正确(请参见需要在URI中编码的字符列表)。
RubyonRails中有一个
1 2 3 4 5 6 7 8 9 10 11 12 13 | base_url = 'http://api.abc.com/v3/avail' arguments = { rev: ENV['REV'], key: ENV['KEY'], locale: 'en_US', currencyCode: currency, arrivalDate: check_in, departureDate: check_out, includeDetails: true, includeRoomImages: true, room1: total_guests } request_url ="#{base_url}?#{arguments.to_query}" |
可以使用数组并联接字符串:
1 2 3 4 5 6 7 8 9 10 11 12 | request_url = [ "http://api.abc.com/v3/avail?", "&rev=#{ENV['REV']}", "&key=#{ENV['KEY']}", "&locale=en_US", "¤cyCode=#{currency}", "&arrivalDate=#{check_in}", "&departureDate=#{check_out}", "&includeDetails=true", "&includeRoomImages=true", "&room1=#{total_guests}", ].join('') |
更简单的是,您可以使用
1 2 3 4 5 6 7 8 9 10 11 12 | request_url = %W( http://api.abc.com/v3/avail? &rev=#{ENV['REV']} &key=#{ENV['KEY']} &locale=en_US ¤cyCode=#{currency} &arrivalDate=#{check_in} &departureDate=#{check_out} &includeDetails=true &includeRoomImages=true &room1=#{total_guests} ).join('') |
号
编辑:当然,Spickermann在上面特别针对URL的更好的实现方法上做了一个很好的说明。但是,如果您不构建URL,只使用字符串,那么上述方法应该可以正常工作。
您可以使用行继续符在Ruby中扩展字符串。例子:
1 2 3 | request_url ="http://api.abc.com/v3/avail?" \ "&rev=#{ENV['REV']}" \ "&key=#{ENV['KEY']}" |
。