ruby-grape / ruby-grape/grape-entity

Expose different types of objects in the same array

Open
#192 8 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

feature question
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.