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.



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

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.



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

def method
  @method
end

#optionsObject

Returns the value of attribute options.



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

def options
  @options
end

Instance Method Details

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



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

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

  call!(target)
end

#call!(target) ⇒ Object

Runs the callback without any validations



20
21
22
# File 'lib/flow_machine/callback.rb', line 20

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

#run_method(target, method) ⇒ Object



32
33
34
# File 'lib/flow_machine/callback.rb', line 32

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

#run_method_or_lambda(target, method) ⇒ Object



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

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)


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

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