Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Allow Model#from_json in the json_serializer plugin to use set_fields…

… if a :fields option is given

Additionally, pass the options hash to set_fields, so you can use
the :missing=>:skip and :missing=>:raise options.
  • Loading branch information...
commit b1bfd6af95284d0b3739efdf8dfe22880f0c5f7b 1 parent dd3ede6
Jeremy Evans authored May 30, 2012
2  CHANGELOG
... ...
@@ -1,5 +1,7 @@
1 1
 === HEAD
2 2
 
  3
+* Allow Model#from_json in the json_serializer plugin to use set_fields if a :fields option is given (jeremyevans)
  4
+
3 5
 * Support :using option to set_column_type on PostgreSQL, to force a specific conversion from the old value to the new value (jeremyevans)
4 6
 
5 7
 * Drop indexes in the reverse order that they were added in the schema dumper (jeremyevans)
9  lib/sequel/plugins/json_serializer.rb
@@ -139,8 +139,13 @@ def inherited(subclass)
139 139
       module InstanceMethods
140 140
         # Parse the provided JSON, which should return a hash,
141 141
         # and call +set+ with that hash.
142  
-        def from_json(json)
143  
-          set(JSON.parse(json))
  142
+        def from_json(json, opts={})
  143
+          h = JSON.parse(json)
  144
+          if fields = opts[:fields]
  145
+            set_fields(h, fields, opts)
  146
+          else
  147
+            set(h)
  148
+          end
144 149
         end
145 150
 
146 151
         # Return a string in JSON format.  Accepts the following
16  spec/extensions/json_serializer_spec.rb
@@ -96,6 +96,22 @@ def name=(v)
96 96
     @artist.id.should == 2
97 97
   end
98 98
 
  99
+  it "should support #from_json to support specific :fields" do
  100
+    @album.from_json('{"name": "AS", "artist_id": 3}', :fields=>['name'])
  101
+    @album.name.should == 'AS'
  102
+    @album.artist_id.should == 2
  103
+  end
  104
+
  105
+  it "should support #from_json to support :missing=>:skip option" do
  106
+    @album.from_json('{"artist_id": 3}', :fields=>['name'], :missing=>:skip)
  107
+    @album.name.should == 'RF'
  108
+    @album.artist_id.should == 2
  109
+  end
  110
+
  111
+  it "should support #from_json to support :missing=>:raise option" do
  112
+    proc{@album.from_json('{"artist_id": 3}', :fields=>['name'], :missing=>:raise)}.should raise_error(Sequel::Error)
  113
+  end
  114
+
99 115
   it "should raise an exception for json keys that aren't associations, columns, or setter methods" do
100 116
     Album.send(:undef_method, :blah=)
101 117
     proc{JSON.parse(@album.to_json(:include=>:blah))}.should raise_error(Sequel::Error)

0 notes on commit b1bfd6a

Please sign in to comment.
Something went wrong with that request. Please try again.