|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require "cgi" |
| 4 | + |
| 5 | +class Object |
| 6 | + # Alias of <tt>to_s</tt>. |
| 7 | + def to_param |
| 8 | + to_s |
| 9 | + end |
| 10 | + |
| 11 | + # Converts an object into a string suitable for use as a URL query string, |
| 12 | + # using the given <tt>key</tt> as the param name. |
| 13 | + def to_query(key) |
| 14 | + "#{CGI.escape(key.to_param)}=#{CGI.escape(to_param.to_s)}" |
| 15 | + end |
| 16 | +end |
| 17 | + |
| 18 | +class NilClass |
| 19 | + # Returns +self+. |
| 20 | + def to_param |
| 21 | + self |
| 22 | + end |
| 23 | +end |
| 24 | + |
| 25 | +class TrueClass |
| 26 | + # Returns +self+. |
| 27 | + def to_param |
| 28 | + self |
| 29 | + end |
| 30 | +end |
| 31 | + |
| 32 | +class FalseClass |
| 33 | + # Returns +self+. |
| 34 | + def to_param |
| 35 | + self |
| 36 | + end |
| 37 | +end |
| 38 | + |
| 39 | +class Array |
| 40 | + # Calls <tt>to_param</tt> on all its elements and joins the result with |
| 41 | + # slashes. This is used by <tt>url_for</tt> in Action Pack. |
| 42 | + def to_param |
| 43 | + collect(&:to_param).join "/" |
| 44 | + end |
| 45 | + |
| 46 | + # Converts an array into a string suitable for use as a URL query string, |
| 47 | + # using the given +key+ as the param name. |
| 48 | + # |
| 49 | + # ['Rails', 'coding'].to_query('hobbies') # => "hobbies%5B%5D=Rails&hobbies%5B%5D=coding" |
| 50 | + def to_query(key) |
| 51 | + prefix = "#{key}[]" |
| 52 | + |
| 53 | + if empty? |
| 54 | + nil.to_query(prefix) |
| 55 | + else |
| 56 | + collect { |value| value.to_query(prefix) }.join "&" |
| 57 | + end |
| 58 | + end |
| 59 | +end |
| 60 | + |
| 61 | +class Hash |
| 62 | + # Returns a string representation of the receiver suitable for use as a URL |
| 63 | + # query string: |
| 64 | + # |
| 65 | + # {name: 'David', nationality: 'Danish'}.to_query |
| 66 | + # # => "name=David&nationality=Danish" |
| 67 | + # |
| 68 | + # An optional namespace can be passed to enclose key names: |
| 69 | + # |
| 70 | + # {name: 'David', nationality: 'Danish'}.to_query('user') |
| 71 | + # # => "user%5Bname%5D=David&user%5Bnationality%5D=Danish" |
| 72 | + # |
| 73 | + # The string pairs "key=value" that conform the query string |
| 74 | + # are sorted lexicographically in ascending order. |
| 75 | + # |
| 76 | + # This method is also aliased as +to_param+. |
| 77 | + def to_query(namespace = nil) |
| 78 | + query = collect do |key, value| |
| 79 | + unless (value.is_a?(Hash) || value.is_a?(Array)) && value.empty? |
| 80 | + value.to_query(namespace ? "#{namespace}[#{key}]" : key) |
| 81 | + end |
| 82 | + end.compact |
| 83 | + |
| 84 | + query.sort! unless namespace.to_s.include?("[]") |
| 85 | + query.join("&") |
| 86 | + end |
| 87 | + |
| 88 | + alias to_param to_query |
| 89 | +end |
0 commit comments