diff options
author | Jeremy Kemper <jeremy@bitsweat.net> | 2009-11-01 11:06:47 +0100 |
---|---|---|
committer | Jeremy Kemper <jeremy@bitsweat.net> | 2009-11-02 17:50:12 -0800 |
commit | b540eca5889d7a28fac39c9ec0df715aa89487ce (patch) | |
tree | 76a8ef40d8a9e99f1dc36a5b526b9a4c9c62567c /activesupport/lib/active_support/core_ext/object/to_param.rb | |
parent | 8935854375a6c08acd617beaec30f6fd09a29ea0 (diff) | |
download | rails-b540eca5889d7a28fac39c9ec0df715aa89487ce.tar.gz rails-b540eca5889d7a28fac39c9ec0df715aa89487ce.tar.bz2 rails-b540eca5889d7a28fac39c9ec0df715aa89487ce.zip |
Consolidate Object#to_param and #to_query core extensions
Diffstat (limited to 'activesupport/lib/active_support/core_ext/object/to_param.rb')
-rw-r--r-- | activesupport/lib/active_support/core_ext/object/to_param.rb | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/activesupport/lib/active_support/core_ext/object/to_param.rb b/activesupport/lib/active_support/core_ext/object/to_param.rb new file mode 100644 index 0000000000..a5e2260791 --- /dev/null +++ b/activesupport/lib/active_support/core_ext/object/to_param.rb @@ -0,0 +1,47 @@ +class Object + # Alias of <tt>to_s</tt>. + def to_param + to_s + end +end + +class NilClass + def to_param + self + end +end + +class TrueClass + def to_param + self + end +end + +class FalseClass + 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 +end + +class Hash + # Converts a hash into a string suitable for use as a URL query string. An optional <tt>namespace</tt> can be + # passed to enclose the param names (see example below). + # + # ==== Examples + # { :name => 'David', :nationality => 'Danish' }.to_query # => "name=David&nationality=Danish" + # + # { :name => 'David', :nationality => 'Danish' }.to_query('user') # => "user%5Bname%5D=David&user%5Bnationality%5D=Danish" + def to_param(namespace = nil) + collect do |key, value| + value.to_query(namespace ? "#{namespace}[#{key}]" : key) + end.sort * '&' + end +end |