Skip to content

Commit

Permalink
Support JSON serialize
Browse files Browse the repository at this point in the history
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 :)
  • Loading branch information
yhirano55 committed Feb 8, 2020
1 parent 45384f8 commit faa6f84
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/active_hash/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions spec/active_hash/base_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit faa6f84

Please sign in to comment.