Module: Memorable::Controller::ClassMethods

Defined in:
lib/memorable/controller.rb

Instance Method Summary collapse

Instance Method Details

#memorize(options = {}, &block) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/memorable/controller.rb', line 66

def memorize(options = {}, &block)
  raise InvalidOptionsError, "if and unless cannot appear at the sametime" if options[:if] && options[:unless]

  if condition = (options[:if] || options[:unless])
    if_condition = !!options[:if]
    if condition.is_a?(Symbol)
      condition_proc = proc { |c| if_condition ? c.send(condition) : !c.send(condition) }
    elsif condition.is_a? Proc
      condition_proc = proc { |c| if_condition ? condition.call(c) : !condition.call(c) }
    else
      raise InvalidOptionsError, "#{condition} is not a valid Proc or controller method."
    end
  end

  raise InvalidOptionsError, "except and only cannot appear at the sametime" if options[:except] && options[:only]

  specified_actions = [options[:except] || options[:only]].flatten.compact.map(&:to_s)
  actions =
    if options.delete(:only)
      specified_actions
    elsif options.delete(:except)
      all_actions - specified_actions
    else
      all_actions
    end

  memorize_actions actions, options, condition_proc
end