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:

  1. don't call current_orders directly in constructor. orders should loaded first time when you're calling either orders_start or orders_acceptance. there risk initializes service when request processing starts because of business rules neither of methods run. in case - called db never consumed result.

  2. in both orders_acceptance , orders_start you're using @current_orders instance variable. it's ok it's fine if call current_orders method multiple times - result same.


Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -