ruby on rails - use memoization in my code -
been told use memoization in code not call function on , over. implementation best way use it? seems redundant. please advise how rid of initialize function.
class orderservice def initialize @current_orders = current_orders end def orders_acceptance @current_orders. with_statuses(:acceptance). select |order| order.acceptance? if order.shopper_notified_at? end end def orders_start @current_orders. with_statuses(:start). select |order| order.start? end end private def current_orders @current_orders ||= begin order.includes(:timestamps). with_statuses( [ :acceptance, :start ] ) end end end
2 tips:
don't call
current_ordersdirectly in constructor. orders should loaded first time when you're calling eitherorders_startororders_acceptance. there risk initializes service when request processing starts because of business rules neither of methods run. in case - called db never consumed result.in both
orders_acceptance,orders_startyou're using@current_ordersinstance variable. it's ok it's fine if callcurrent_ordersmethod multiple times - result same.
Comments
Post a Comment