Class: FlowMachine::Callback

Inherits:
Object
  • Object
show all
Defined in:
lib/flow_machine/callback.rb

Direct Known Subclasses

StateCallback

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args, &block) ⇒ Callback

Returns a new instance of Callback.



6
7
8
9
10
# File 'lib/flow_machine/callback.rb', line 6

def initialize(*args, &block)
  @options = args.extract_options!
  @method = args.shift unless block
  @block = block
end

Instance Attribute Details

#methodObject

Returns the value of attribute method.



5
6
7
# File 'lib/flow_machine/callback.rb', line 5

def method
  @method
end

#optionsObject

Returns the value of attribute options.



5
6
7
# File 'lib/flow_machine/callback.rb', line 5

def options
  @options
end

Instance Method Details

#call(target, changes = {}) ⇒ Object



12
13
14
15
# File 'lib/flow_machine/callback.rb', line 12

def call(target, changes = {})
  return unless will_run? target, changes
  call!(target)
end

#call!(target) ⇒ Object

Runs the callback without any validations



18
19
20
# File 'lib/flow_machine/callback.rb', line 18

def call!(target)
  run_method_or_lambda(target, method.presence || @block)
end

#run_method(target, method) ⇒ Object



30
31
32
# File 'lib/flow_machine/callback.rb', line 30

def run_method(target, method)
  target.send(method)
end

#run_method_or_lambda(target, method) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/flow_machine/callback.rb', line 22

def run_method_or_lambda(target, method)
  if method.respond_to? :call # is it a lambda
    target.instance_exec &method
  else
    run_method(target, method)
  end
end

#will_run?(target, changes = {}) ⇒ Boolean

Returns:

  • (Boolean)


34
35
36
37
38
39
40
41
42
# File 'lib/flow_machine/callback.rb', line 34

def will_run?(target, changes = {})
  if options[:if]
    [*options[:if]].all? { |m| run_method_or_lambda(target, m) }
  elsif options[:unless]
    [*options[:unless]].none? { |m| run_method_or_lambda(target, m) }
  else
    true
  end
end