ruby-grape / ruby-grape/grape-entity
#as_json confusion in Rails
Nobody has claimed this yet.
- Dominant language
- Ruby
- Stars
- 729
- Forks
- 154
- PR merge metrics
- No merged PRs in 30d
Description
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?
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the Entities::User.represent(user).as_json example and inspect how the root element, the returned Hash, and Grape::Entity#as_json interact. Done should mean the resulting root-wrapped Hash has predictable key handling, but the issue does not specify the desired behavior or name files and tests to change.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rails, ruby
- Domain
- api, backend
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 30/100