Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building arbitrary URLs incrementally in Ruby on Rails

I have a URL in a string. What is the most concise way to add some parameters to it?

e.g.

base = 'http://example.com'
uri1 = some_magical_method(base, :p1 => 'v1') # => http://example.com/?p1=v1
uri2 = some_magical_method(uri1, :p2 => 'v2') # => http://example.com/?p1=v1&p2=v2
uri3 = some_magical_method(uri2, :p3 => nil)  # => http://example.com/?p1=v1&p2=v2

1) In Ruby?

2) In Rails?

like image 825
user1015384 Avatar asked Nov 07 '11 16:11

user1015384


2 Answers

In Rails, where ActiveSupport is available, the easiest way is to construct a hash, then to call #to_query on it.

>> params = {}
>> params[:foo] = "bar"
>> params[:baz] = "bang"
>> params.to_query
=> "baz=bang&foo=bar"

In plain Ruby, the same applies, but you'll need to write the encoder yourself:

require 'cgi'
def to_query(hsh)
  hsh.map {|k, v| "#{k}=#{CGI::escape v}" }.join("&")
end

params = {}
params[:foo] = "bar"
params[:baz] = "bang"

to_query params
=> "baz=bang&foo=bar"
like image 159
Chris Heald Avatar answered Oct 11 '22 12:10

Chris Heald


require 'open-uri'

def params_to_query(params)
  params.map {|p, v| "#{p}=#{URI.escape(v.to_s)}"}.join('&')
end

def append_url(url, params = {})
  uri = URI.parse(url)
  uri.query = uri.query.nil? ? params_to_query(params) : [uri.query, params_to_query(params)].join('&') unless params.empty?
  uri.to_s
end

puts append_url('http://example.com', {:query => 'my_example'} # "http://example.com?query=my_example"
like image 40
Oleksandr Skrypnyk Avatar answered Oct 11 '22 12:10

Oleksandr Skrypnyk