Victor Victor - 6 months ago 32
Ruby Question

Tidy long string in Ruby

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.

Answer

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('')