3

I'm trying to build a set of APIs using Rails and Grape. The User model like below:

{
    "email": "foo@bar.com"
    "name": "Foo Bar"
}

Now, at the API presentation level, I want a user object be like:

{
    "object": "User"
    "email": "foo@bar.com"
    "name": "Foo Bar"
}

Since I'm using Grape Entity gem to expose my models, hence the question really is: How to add an extra CONSTANT-value attribute to a Grape Entity class? Appreciate your help!

fengye87
  • 2,433
  • 4
  • 24
  • 41

1 Answers1

5

You can add an extra field by adding a function to the class like this :

class XXX < Grape::Entity
    expose :object_name
    expose :email
    expose :name

    private
    def object_name
        "User"
    end
end

But if the function's name is object, it won't work. You have choose another name for this field.

For more options, you can also use a block like this, in this case, no matter what the field name you're using.

class XXX < Grape::Entity
    expose :object do |you_have_to_set_a_parameter_here|
                "User"
            end
    expose :email
    expose :name
end
Thuc Hung
  • 130
  • 1
  • 1
  • 7