How to expose decorator attributes in Grape Entity

174 views Asked by At

I'm working on exposing some data to a mobile client through the API. Some of that data is defined in a decorator.

app/decorators/customer_opportunity_decorator.rb

  def potential_savings
    return 'N/A' if opportunity.nil?

    multiplier = Customer.get_multiplier(...)
 
    return 'N/A' if multiplier.blank?

    ...more logic
  end

We're using Grape Entities in our API layer and I'm not sure about how to pass this logic through the API. It doesn't seem like it should live in a decorator if being exposed as an API field.

module Entities
    class Opportunity < BaseEntity
        expose :id
        expose :name
        expose :potential_savings # need this field on the API

...

And then there's an api model ApiOpportunity

class ApiOpportunity
  attr_reader :id, :name, :potential_savings

  def initialize(opportunity)
    @id = opportunity.id
    @name = opportunity.name
    @potential_savings = opportunity.potential_savings # this approach doesn't seem to work
  end
end

Is this logic that I should move elsewhere? Is it fine to remain as a decorator and somehow pass through in the API?

0

There are 0 answers