ruby-grape / ruby-grape/grape-entity
Expose different types of objects in the same array
Nobody has claimed this yet.
- Dominant language
- Ruby
- Stars
- 729
- Forks
- 154
- PR merge metrics
- No merged PRs in 30d
Description
I'd like to return a JSON array that has two different types of models, each with its own Grape::Entity. So for example, I have a package, which has this
class Entity < Grape::Entity
expose :id, :foo
expose :image, format_with: :image_absolute_url
end
And then I have experience, which has this
class Entity < Grape::Entity
expose :id, :bar
expose :image, format_with: :image_absolute_url
end
In my API call, I create an array like this.
present [ Package.last, Experience.last ]
One way I thought of was to define a new entity, and pass it in using "with", but then I'm just repeating my previous definitions. And I also wasn't sure how to do it besides something like
class NewEntity < Grape::Entity
expose :id, if: lambda { |object, options| object.is_a?(Package) }
expose :bar, if: lambda { |object, options| object.is_a?(Experience) }
end
Is there a better solution for this?
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 Grape::Entity definitions and the present [Package.last, Experience.last] and with usage described in the issue. Review how entities select fields for each object type, then determine whether mixed arrays can be supported without repeating exposures; done means a concrete supported approach or a documented limitation.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- ruby
- Domain
- api
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100