adomokos / light-service

Series of Actions with an emphasis on simplicity.
MIT License
837 stars 67 forks source link

Accessing context values directly in executed block #135

Closed robwilliams closed 6 years ago

robwilliams commented 6 years ago

In the README there is an example action:

class CalculatesOrderTaxAction
  extend ::LightService::Action
  expects :order, :tax_percentage

  executed do |context|
    order.tax = (order.total * (tax_percentage/100)).round(2)
  end
end

This doesn't actually work, order has to be accessed through context, it's not available directly in the executed block.

I've actually hit this issue myself and it would be nice to be able to reference the items in the context that have been defined with expects without the prefix..

My workaround at the moment is to assign the variables myself:

class CalculatesOrderTaxAction
  extend ::LightService::Action
  expects :order, :tax_percentage

  executed do |context|
    order = context.order
    tax_percentage = context.tax_percentage

    order.tax = (order.total * (tax_percentage/100)).round(2)
  end
end

Do you think this kind of sugar is worth adding?

adomokos commented 6 years ago

Thank you for catching an error in the README example! I'll fix it today.

I don't mind accessing variables from the context by referring to it via the context, that way I know where that value is coming from. Setting it globally might go against the idea of LightService, where I wanted to decouple state from behavior.

adomokos commented 6 years ago

See this commit to fix it. Please submit a PR if you think README needs more TLC.

Thanks again!