Extracted logic into a presenter to separate responsibilities and to move expiration date and title logic into a new object so it could be reused in different places:
data = EnabledPromotionPresenter.new(promotion:, purchase:).show
render json: jsend(status: response.status, data:)
class EnabledPromotionPresenter
attr_reader :promotion, :purchase
def initialize(promotion:, purchase:)
@promotion = promotion
@purchase = purchase
end
def show
return {} unless promotion
cashback_promotion = Promotions::Cashback.new(promotion:, purchase:)
{
title: cashback_promotion.title,
amount: cashback_promotion.amount,
expiration_date: cashback_promotion.expiration_date
}
end
end
Starting from ruby 3.4, that code could be written with it as default block parameter: arr.each { it.do_something } but I haven’t used it yet. Do you like that new syntax?