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