0

I have a method in Ruby, which needs an API URL:

  request_url = "http://api.abc.com/v3/avail?rev=#{ENV['REV']}&key=#{ENV['KEY']}&locale=en_US&currencyCode=#{currency}&arrivalDate=#{check_in}&departureDate=#{check_out}&includeDetails=true&includeRoomImages=true&room1=#{total_guests}"

I want to format it to be more readable. It should take arguments.

request_url = "http://api.abc.com/v3/avail?
  &rev=#{ENV['REV']}
  &key=#{ENV['KEY']}
  &locale=en_US
  &currencyCode=#{currency}
  &arrivalDate=#{check_in}
  &departureDate=#{check_out}
  &includeDetails=true
  &includeRoomImages=true
  &room1=#{total_guests}"

But of course there's line break. I tried heredoc, but I want it to be in one line.

Victor
  • 13,010
  • 18
  • 83
  • 146

3 Answers3

4

I would prefer to not build URI queries by joining strings, because that might lead to URLs that are not correctly encoded (see a list of characters that need to be encoded in URIs).

There is the Hash#to_query method in Ruby on Rails that does exactly what you need and it ensure that the parameters are correctly URI encoded:

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}"
spickermann
  • 100,941
  • 9
  • 101
  • 131
2

You could use an array and join the strings:

request_url = [
  "http://api.abc.com/v3/avail?",
  "&rev=#{ENV['REV']}",
  "&key=#{ENV['KEY']}",
  "&locale=en_US",
  "&currencyCode=#{currency}",
  "&arrivalDate=#{check_in}",
  "&departureDate=#{check_out}",
  "&includeDetails=true",
  "&includeRoomImages=true",
  "&room1=#{total_guests}",
].join('')

Even easier, you can use the %W array shorthand notation so you don't have to write out all the quotes and commas:

request_url = %W(
  http://api.abc.com/v3/avail?
  &rev=#{ENV['REV']}
  &key=#{ENV['KEY']}
  &locale=en_US
  &currencyCode=#{currency}
  &arrivalDate=#{check_in}
  &departureDate=#{check_out}
  &includeDetails=true
  &includeRoomImages=true
  &room1=#{total_guests}
).join('')

Edit: Of course, spickermann makes a very good point above on better ways to accomplish this specifically for URLs. However, if you're not constructing a URL and just working with strings, the above methods should work fine.

Community
  • 1
  • 1
JKillian
  • 18,061
  • 8
  • 41
  • 74
0

You can extend strings in Ruby using the line continuation operator. Example:

request_url = "http://api.abc.com/v3/avail?" \
  "&rev=#{ENV['REV']}" \
  "&key=#{ENV['KEY']}"
Gerry Shaw
  • 9,178
  • 5
  • 41
  • 45