diff options
Diffstat (limited to 'activemodel/lib/active_model/serializers/json.rb')
-rw-r--r-- | activemodel/lib/active_model/serializers/json.rb | 39 |
1 files changed, 36 insertions, 3 deletions
diff --git a/activemodel/lib/active_model/serializers/json.rb b/activemodel/lib/active_model/serializers/json.rb index e4c7553cb8..a4252b995d 100644 --- a/activemodel/lib/active_model/serializers/json.rb +++ b/activemodel/lib/active_model/serializers/json.rb @@ -1,5 +1,4 @@ require 'active_support/json' -require 'active_support/core_ext/class/attribute' module ActiveModel # == Active Model JSON Serializer @@ -19,8 +18,8 @@ module ActiveModel # passed through +options+. # # The option <tt>include_root_in_json</tt> controls the top-level behavior - # of +as_json+. If true +as_json+ will emit a single root node named after - # the object's type. The default value for <tt>include_root_in_json</tt> + # of +as_json+. If +true+, +as_json+ will emit a single root node named + # after the object's type. The default value for <tt>include_root_in_json</tt> # option is +false+. # # user = User.find(1) @@ -101,6 +100,40 @@ module ActiveModel end end + # Sets the model +attributes+ from a JSON string. Returns +self+. + # + # class Person + # include ActiveModel::Serializers::JSON + # + # attr_accessor :name, :age, :awesome + # + # def attributes=(hash) + # hash.each do |key, value| + # instance_variable_set("@#{key}", value) + # end + # end + # + # def attributes + # instance_values + # end + # end + # + # json = { name: 'bob', age: 22, awesome:true }.to_json + # person = Person.new + # person.from_json(json) # => #<Person:0x007fec5e7a0088 @age=22, @awesome=true, @name="bob"> + # person.name # => "bob" + # person.age # => 22 + # person.awesome # => true + # + # The default value for +include_root+ is +false+. You can change it to + # +true+ if the given JSON string includes a single root node. + # + # json = { person: { name: 'bob', age: 22, awesome:true } }.to_json + # person = Person.new + # person.from_json(json) # => #<Person:0x007fec5e7a0088 @age=22, @awesome=true, @name="bob"> + # person.name # => "bob" + # person.age # => 22 + # person.awesome # => true def from_json(json, include_root=include_root_in_json) hash = ActiveSupport::JSON.decode(json) hash = hash.values.first if include_root |