Add constant attribute to Grape entity

1.7k views Asked by At

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

{
    "email": "[email protected]"
    "name": "Foo Bar"
}

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

{
    "object": "User"
    "email": "[email protected]"
    "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!

1

There are 1 answers

0
Thuc Hung On BEST ANSWER

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