Sha256: f05ba21da098401860c7e92b2c208e24615b84ab1e68789b20f963a5a39c407f

Contents?: true

Size: 1.83 KB

Versions: 8

Compression:

Stored size: 1.83 KB

Contents

class Object
  # Alias of <tt>to_s</tt>.
  def to_param
    to_s
  end

  # Converts an object into a string suitable for use as a URL query string,
  # using the given <tt>key</tt> as the param name.
  def to_query(key)
    require 'cgi' unless defined?(CGI) && defined?(CGI::escape)
    "#{CGI.escape(key.to_param)}=#{CGI.escape(to_param.to_s)}"
  end
end

class NilClass
  # Returns +self+.
  def to_param
    self
  end
end

class TrueClass
  # Returns +self+.
  def to_param
    self
  end
end

class FalseClass
  # Returns +self+.
  def to_param
    self
  end
end

class Array
  # Calls <tt>to_param</tt> on all its elements and joins the result with
  # slashes. This is used by <tt>url_for</tt> in Action Pack.
  def to_param
    collect { |e| e.to_param }.join '/'
  end

  # Converts an array into a string suitable for use as a URL query string,
  # using the given +key+ as the param name.
  #
  #   ['Rails', 'coding'].to_query('hobbies') # => "hobbies%5B%5D=Rails&hobbies%5B%5D=coding"
  def to_query(key)
    prefix = "#{key}[]"
    collect { |value| value.to_query(prefix) }.join '&'
  end
end

class Hash
  # Returns a string representation of the receiver suitable for use as a URL
  # query string:
  #
  #   {name: 'David', nationality: 'Danish'}.to_query
  #   # => "name=David&nationality=Danish"
  #
  # An optional namespace can be passed to enclose the param names:
  #
  #   {name: 'David', nationality: 'Danish'}.to_query('user')
  #   # => "user[name]=David&user[nationality]=Danish"
  #
  # The string pairs "key=value" that conform the query string
  # are sorted lexicographically in ascending order.
  #
  # This method is also aliased as +to_param+.
  def to_query(namespace = nil)
    collect do |key, value|
      value.to_query(namespace ? "#{namespace}[#{key}]" : key)
    end.sort * '&'
  end

  alias_method :to_param, :to_query
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
activesupport-4.0.13 lib/active_support/core_ext/object/to_query.rb
activesupport-4.0.13.rc1 lib/active_support/core_ext/object/to_query.rb
activesupport-4.0.11.1 lib/active_support/core_ext/object/to_query.rb
activesupport-4.0.12 lib/active_support/core_ext/object/to_query.rb
activesupport-4.0.11 lib/active_support/core_ext/object/to_query.rb
activesupport-4.0.10 lib/active_support/core_ext/object/to_query.rb
activesupport-4.0.10.rc2 lib/active_support/core_ext/object/to_query.rb
activesupport-4.0.10.rc1 lib/active_support/core_ext/object/to_query.rb