Froze rails gems
[depot.git] / vendor / rails / activerecord / lib / active_record / serializers / json_serializer.rb
1 module ActiveRecord #:nodoc:
2 module Serialization
3 def self.included(base)
4 base.cattr_accessor :include_root_in_json, :instance_writer => false
5 base.extend ClassMethods
6 end
7
8 # Returns a JSON string representing the model. Some configuration is
9 # available through +options+.
10 #
11 # Without any +options+, the returned JSON string will include all
12 # the model's attributes. For example:
13 #
14 # konata = User.find(1)
15 # konata.to_json
16 # # => {"id": 1, "name": "Konata Izumi", "age": 16,
17 # "created_at": "2006/08/01", "awesome": true}
18 #
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:
21 #
22 # konata.to_json(:only => [ :id, :name ])
23 # # => {"id": 1, "name": "Konata Izumi"}
24 #
25 # konata.to_json(:except => [ :id, :created_at, :age ])
26 # # => {"name": "Konata Izumi", "awesome": true}
27 #
28 # To include any methods on the model, use <tt>:methods</tt>.
29 #
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"}
34 #
35 # To include associations, use <tt>:include</tt>.
36 #
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"}]}
42 #
43 # 2nd level and higher order associations work as well:
44 #
45 # konata.to_json(:include => { :posts => {
46 # :include => { :comments => {
47 # :only => :body } },
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}}"
58 else
59 JsonSerializer.new(self, options).to_s
60 end
61 end
62
63 def from_json(json)
64 self.attributes = ActiveSupport::JSON.decode(json)
65 self
66 end
67
68 class JsonSerializer < ActiveRecord::Serialization::Serializer #:nodoc:
69 def serialize
70 serializable_record.to_json
71 end
72 end
73
74 module ClassMethods
75 def json_class_name
76 @json_class_name ||= name.demodulize.underscore.inspect
77 end
78 end
79 end
80 end