Skip to content

Expose different types of objects in the same array #192

Open
@waynn

Description

@waynn

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?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions