ruby-on-railsrestgrape-entity

Add constant attribute to Grape entity


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!


Solution

  • 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