grape-entity icon indicating copy to clipboard operation
grape-entity copied to clipboard

#as_json confusion in Rails

Open wyattisimo opened this issue 12 years ago • 2 comments

If I'm using grape-entity in Rails, and I do something like this:

module Entities
  class User < Grape::Entity
    root :users, :user
    expose :id
    expose :name
  end
end

and then I do something like this:

Entities::User.represent(user).as_json

I'll end up with something like this:

{ "user" => { :id => 1234, :name => "Danny Boy" } }

Notice that the keys are a mixture of symbols and strings. This is because the result of Entities::User.represent(user) is a Hash, and I think the as_json method there actually comes from ActiveModel, which uses strings for the keys. But the value for the "user" key is a Grape::Entity, and Grape::Entity#as_json uses symbols for the keys.

I think it would be good to have better control over the Hash that results from using a root element. Maybe create a subclass of Hash that implements as_json and any other relevant/useful methods?

Thoughts?

wyattisimo avatar Nov 24 '13 02:11 wyattisimo

I would be down with making sure all keys are symbols here, but I am not sure that patching Hash is the right way to go. I would write a spec for this in grape-entity, first, then track down where we insert "user".

dblock avatar Nov 24 '13 16:11 dblock

This issue is still alive and well today in 2021. The nested entity is deceivingly not a hash but Grape::Entity::Exposure::NestingExposure::OutputBuilder which is why it's "not consistent".

synth avatar Apr 19 '21 05:04 synth