ruby-on-railsruby-grapegrape-apigrape-entity

Apply alias for loop in grape entity


I would like to get the following JSON.

[{"Product":{"CountryName":4848, }},{"Product":{"CountryName":700}]


module API
  module Entities
    class Example < Grape::Entity
      expose(:product) do
        expose(:country_name) do |product, options|
          product.country.name
        end
      end
    end
  end
end

The parameters are product and name. I would like to return Product, ProductName.

How to apply alias for looping elements in grape entity framework?


Solution

  • In your case, this would give :

    module API
      module Entities
        class Product < Grape::Entity
          expose 'Product' do
            # You expose the result of the country_name method, 
            # and use an alias to customise the attribute name
            expose :country_name, as: 'CountryName'
          end
    
          private
    
          # Method names are generally snake_case in ruby, so it feels
          # more natural to use a snake_case method name and alias it
          def country_name
            object.country.name
          end
        end
      end
    end
    

    And in your endpoint, you specify the entity that must be used to serialize the Products instances. In my example, you may have noticed that I took the liberty of renaming the entity to Product, which would give us in the endpoint:

    # /products endpoint
    resources :products do
      get '/' do
        present Product.all, with: API::Entities::Product
      end
    end
    

    Which should get you this kind of output, as expected:

    [
        { "Product": { "CountryName": "test 1" } },
        { "Product": { "CountryName": "test 2" } }
    ]