Created
July 16, 2012 20:04
-
-
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 file contains hidden or 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
| #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