diff options
author | Godfrey Chan <godfreykfc@gmail.com> | 2014-07-05 14:23:01 -0700 |
---|---|---|
committer | Godfrey Chan <godfreykfc@gmail.com> | 2014-07-05 14:34:13 -0700 |
commit | a03097759bd7103bb9db253e7ba095f011453f75 (patch) | |
tree | 4a20132e2c7fe66f25e7170ae751d3b67d92b3f5 /activerecord/lib | |
parent | acec038b38dc248c5c2f350de69ab89d9b1402c7 (diff) | |
download | rails-a03097759bd7103bb9db253e7ba095f011453f75.tar.gz rails-a03097759bd7103bb9db253e7ba095f011453f75.tar.bz2 rails-a03097759bd7103bb9db253e7ba095f011453f75.zip |
Merge pull request #16059 from jenncoop/json-serialized-attr
Fixed issue with ActiveRecord serialize object as JSON
Conflicts:
activerecord/CHANGELOG.md
activerecord/lib/active_record/attribute_methods/serialization.rb
Diffstat (limited to 'activerecord/lib')
-rw-r--r-- | activerecord/lib/active_record.rb | 1 | ||||
-rw-r--r-- | activerecord/lib/active_record/attribute_methods/serialization.rb | 7 | ||||
-rw-r--r-- | activerecord/lib/active_record/coders/json.rb | 13 |
3 files changed, 20 insertions, 1 deletions
diff --git a/activerecord/lib/active_record.rb b/activerecord/lib/active_record.rb index 17b00bbaea..9028970a3d 100644 --- a/activerecord/lib/active_record.rb +++ b/activerecord/lib/active_record.rb @@ -97,6 +97,7 @@ module ActiveRecord module Coders autoload :YAMLColumn, 'active_record/coders/yaml_column' + autoload :JSON, 'active_record/coders/json' end module AttributeMethods diff --git a/activerecord/lib/active_record/attribute_methods/serialization.rb b/activerecord/lib/active_record/attribute_methods/serialization.rb index 734d94865a..264ce2bdfa 100644 --- a/activerecord/lib/active_record/attribute_methods/serialization.rb +++ b/activerecord/lib/active_record/attribute_methods/serialization.rb @@ -37,7 +37,12 @@ module ActiveRecord # serialize :preferences, Hash # end def serialize(attr_name, class_name_or_coder = Object) - coder = if [:load, :dump].all? { |x| class_name_or_coder.respond_to?(x) } + # When ::JSON is used, force it to go through the Active Support JSON encoder + # to ensure special objects (e.g. Active Record models) are dumped correctly + # using the #as_json hook. + coder = if class_name_or_coder == ::JSON + Coders::JSON + elsif [:load, :dump].all? { |x| class_name_or_coder.respond_to?(x) } class_name_or_coder else Coders::YAMLColumn.new(class_name_or_coder) diff --git a/activerecord/lib/active_record/coders/json.rb b/activerecord/lib/active_record/coders/json.rb new file mode 100644 index 0000000000..0f60b6dab2 --- /dev/null +++ b/activerecord/lib/active_record/coders/json.rb @@ -0,0 +1,13 @@ +module ActiveRecord + module Coders # :nodoc: + class JSON # :nodoc: + def self.dump(obj) + ActiveSupport::JSON.encode(obj) + end + + def self.load(json) + ActiveSupport::JSON.decode(json) + end + end + end +end |