0

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?

jordan
  • 9,570
  • 9
  • 43
  • 78
  • Are you passing the decorator through Grape? If so then this is fine. If not you will need to move this to the model. Just need a bit more context on how you are rending the object in the grape api – engineersmnky Dec 02 '22 at 21:21
  • @engineersmnky have added info to the post, but I attempted to pass this info through an api model. It doesn't work as expected. – jordan Dec 02 '22 at 21:26
  • For that to work `oppurtunity` in `ApiDesiredPlacement#new` needs to be a `CustomerOppurtunityDecorator` object. Otherwise you can move this logic to the model. Not sure why you need the `ApiDesiredPlacement` object I would just use your decorator for both – engineersmnky Dec 02 '22 at 21:34

0 Answers0