Skip to content

Instantly share code, notes, and snippets.

@miguelperez
Created July 16, 2012 20:04
Show Gist options
  • Select an option

  • Save miguelperez/3124704 to your computer and use it in GitHub Desktop.

Select an option

Save miguelperez/3124704 to your computer and use it in GitHub Desktop.
Query params. Given a hash|array it will return a query string for a url.
#This module lets us create a query string from a hash or array.
module QueryParams
def self.encode(value, key = nil, sep = '&')
case value
when Hash then value.map { |k,v| encode(v, append_key(key,k), sep) }.join(sep)
when Array then value.map { |v| encode(v, "#{key}[]", sep) }.join(sep)
when nil then ''
else
if value.to_s.present?
"#{key}=#{CGI.escape(value.to_s)}"
else
""
end
end
end
private
def self.append_key(root_key, key)
root_key.nil? ? key : "#{root_key}[#{key.to_s}]"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment