Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

root/trunk/activesupport/lib/active_support/json/encoders/hash.rb

Revision 9093, 1.7 kB (checked in by pratik, 5 months ago)

Improve documentation.

Line 
1 class Hash
2   # Returns a JSON string representing the hash.
3   #
4   # Without any +options+, the returned JSON string will include all
5   # the hash keys. For example:
6   #
7   #   { :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_json
8   #   # => {"name": "Konata Izumi", 1: 2, "age": 16}
9   #
10   # The keys in the JSON string are unordered due to the nature of hashes.
11   #
12   # The <tt>:only</tt> and <tt>:except</tt> options can be used to limit the
13   # attributes included, and will accept 1 or more hash keys to include/exclude.
14   #
15   #   { :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_json(:only => [:name, 'age'])
16   #   # => {"name": "Konata Izumi", "age": 16}
17   #
18   #   { :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_json(:except => 1)
19   #   # => {"name": "Konata Izumi", "age": 16}
20   #
21   # The +options+ also filter down to any hash values. This is particularly
22   # useful for converting hashes containing ActiveRecord objects or any object
23   # that responds to options in their <tt>to_json</tt> method. For example:
24   #
25   #   users = User.find(:all)
26   #   { :users => users, :count => users.size }.to_json(:include => :posts)
27   #
28   # would pass the <tt>:include => :posts</tt> option to <tt>users</tt>,
29   # allowing the posts association in the User model to be converted to JSON
30   # as well.
31   def to_json(options = {}) #:nodoc:
32     hash_keys = self.keys
33
34     if options[:except]
35       hash_keys = hash_keys - Array(options[:except])
36     elsif options[:only]
37       hash_keys = hash_keys & Array(options[:only])
38     end
39
40     returning result = '{' do
41       result << hash_keys.map do |key|
42         "#{ActiveSupport::JSON.encode(key)}: #{ActiveSupport::JSON.encode(self[key], options)}"
43       end * ', '
44       result << '}'
45     end
46   end
47 end
Note: See TracBrowser for help on using the browser.