Skip to content

Instantly share code, notes, and snippets.

@chikathreesix
Last active August 29, 2015 14:18
Show Gist options
  • Save chikathreesix/5fd68597274aaf43e4ac to your computer and use it in GitHub Desktop.
Save chikathreesix/5fd68597274aaf43e4ac to your computer and use it in GitHub Desktop.
Convert from Hash to Rails query
require 'cgi'
def to_query(param, namespace = nil)
case param
when Hash
param.collect do |key, value|
unless (value.is_a?(Hash) || value.is_a?(Array)) && value.empty?
to_query(value, namespace ? "#{namespace}[#{key}]" : key)
end
end.compact.sort! * '&'
when Array
prefix = "#{namespace}[]"
if param.empty?
to_query(nil, prefix)
else
param.collect { |value| to_query(value, prefix) }.join '&'
end
else
"#{CGI.escape(namespace.to_s)}=#{CGI.escape(param.to_s)}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment