The scenario of the gem is when you have an attribute on model that value depends of a calculation of other model's attribute which attribute's model related. AttributeDependsCalculator will help you solve the case
- Ruby 2.0+
- Rails 4.0+
Add this line to your application's Gemfile:
gem 'attribute-depends-calculator'And then execute:
$ bundle
Assume you have model order and order-item
class Order < ActiveRecord::Base
has_many :order_items
depend total_price: {order_items: :price}
end
class OrderItem < ActiveRecord::Base
belongs_to :order
endAnd you can
order = Order.first
order.total_price
#=> 100.0
order.order_items.pluck(:price)
#=> [50.0, 50.0]
order_item = order.order_items.first
order_item.update(price: 100)
order.reload.total_price
#=> 150.0As above show the price of order automatically update when whatever order_items changes
The options operator had two cateogries of value, the default value of the gem is expression sum
class Order < ActiveRecord::Base
has_many :order_items
depend total_price: {order_items: :price, operator: :+} # or :*
endThe following expression can be use to calculate the collection of depends attributes
sum
class Order < ActiveRecord::Base
...
depend total_price: {order_items: :price, operator: :sum} # default
endaverage
class Order < ActiveRecord::Base
...
depend avg_price: {order_items: :price, operator: :average}
endcount
class Order < ActiveRecord::Base
...
depend order_items_count: {order_items: :price, operator: :count}
endminimum
class Order < ActiveRecord::Base
...
depend min_price: {order_items: :price, operator: :minimum}
endmaximum
class Order < ActiveRecord::Base
...
depend max_price: {order_items: :price, operator: :maximum}
endProc
Proc can be passing in operator option, and the only one params is the active reload of the depended relate Model
class Order < ActiveRecord::Base
...
depend discount_price: {order_items: :price, operator: -> (items) { items.sum(:price) * discount } }
endBug reports and pull requests are welcome on GitHub
MIT © Falm