From faa6f84ba39fa7b08ee41cc5c7dbe0b61d3e4ca5 Mon Sep 17 00:00:00 2001 From: Yoshiyuki Hirano Date: Sat, 8 Feb 2020 20:46:32 +0900 Subject: [PATCH] Support JSON serialize If it use active hash with web api responses, `as_json` behavior is different between active hash's instance and active model's instance. ``` 1) ActiveHash Base #as_json returns a hash Failure/Error: expect(country.as_json).to eq({"id" => 1, "name" => "US", "language" => "English"}) expected: {"id"=>1, "name"=>"US", "language"=>"English"} got: {"attributes"=>{"id"=>1, "name"=>"US", "language"=>"English"}} ``` We don't need `attributes` route key. If it includes `ActiveModel::Serializers::JSON`, behavior of active hash's instance would be as same as a behavior active model's instance. Thanks :) --- lib/active_hash/base.rb | 1 + spec/active_hash/base_spec.rb | 12 ++++++++++++ 2 files changed, 13 insertions(+) diff --git a/lib/active_hash/base.rb b/lib/active_hash/base.rb index 5a14f980..5357bcb9 100644 --- a/lib/active_hash/base.rb +++ b/lib/active_hash/base.rb @@ -61,6 +61,7 @@ def normalize(v) if Object.const_defined?(:ActiveModel) extend ActiveModel::Naming include ActiveModel::Conversion + include ActiveModel::Serializers::JSON else def to_param id.present? ? id.to_s : nil diff --git a/spec/active_hash/base_spec.rb b/spec/active_hash/base_spec.rb index 7935eec0..cb9f3c81 100644 --- a/spec/active_hash/base_spec.rb +++ b/spec/active_hash/base_spec.rb @@ -1531,4 +1531,16 @@ class Book < ActiveRecord::Base end end + describe "#as_json" do + before do + Country.data = [ + {:id => 1, :name => "US", :language => 'English'} + ] + end + + it "returns a hash" do + country = Country.find(1) + expect(country.as_json.stringify_keys).to eq({"id" => 1, "name" => "US", "language" => "English"}) + end + end end