Last active
August 29, 2015 14:18
-
-
Save chikathreesix/5fd68597274aaf43e4ac to your computer and use it in GitHub Desktop.
Convert from Hash to Rails query
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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