1 module ActiveRecord
#:nodoc:
3 def self.included(base
)
4 base
.cattr_accessor
:include_root_in_json, :instance_writer => false
5 base
.extend ClassMethods
8 # Returns a JSON string representing the model. Some configuration is
9 # available through +options+.
11 # Without any +options+, the returned JSON string will include all
12 # the model's attributes. For example:
14 # konata = User.find(1)
16 # # => {"id": 1, "name": "Konata Izumi", "age": 16,
17 # "created_at": "2006/08/01", "awesome": true}
19 # The <tt>:only</tt> and <tt>:except</tt> options can be used to limit the attributes
20 # included, and work similar to the +attributes+ method. For example:
22 # konata.to_json(:only => [ :id, :name ])
23 # # => {"id": 1, "name": "Konata Izumi"}
25 # konata.to_json(:except => [ :id, :created_at, :age ])
26 # # => {"name": "Konata Izumi", "awesome": true}
28 # To include any methods on the model, use <tt>:methods</tt>.
30 # konata.to_json(:methods => :permalink)
31 # # => {"id": 1, "name": "Konata Izumi", "age": 16,
32 # "created_at": "2006/08/01", "awesome": true,
33 # "permalink": "1-konata-izumi"}
35 # To include associations, use <tt>:include</tt>.
37 # konata.to_json(:include => :posts)
38 # # => {"id": 1, "name": "Konata Izumi", "age": 16,
39 # "created_at": "2006/08/01", "awesome": true,
40 # "posts": [{"id": 1, "author_id": 1, "title": "Welcome to the weblog"},
41 # {"id": 2, author_id: 1, "title": "So I was thinking"}]}
43 # 2nd level and higher order associations work as well:
45 # konata.to_json(:include => { :posts => {
46 # :include => { :comments => {
48 # :only => :title } })
49 # # => {"id": 1, "name": "Konata Izumi", "age": 16,
50 # "created_at": "2006/08/01", "awesome": true,
51 # "posts": [{"comments": [{"body": "1st post!"}, {"body": "Second!"}],
52 # "title": "Welcome to the weblog"},
53 # {"comments": [{"body": "Don't think too hard"}],
54 # "title": "So I was thinking"}]}
55 def to_json(options
= {})
56 if include_root_in_json
57 "{#{self.class.json_class_name}: #{JsonSerializer.new(self, options).to_s}}"
59 JsonSerializer
.new(self, options
).to_s
64 self.attributes
= ActiveSupport
::JSON.decode(json
)
68 class JsonSerializer
< ActiveRecord
::Serialization::Serializer #:nodoc:
70 serializable_record
.to_json
76 @json_class_name ||= name
.demodulize
.underscore
.inspect