Class: FiniteMachine::Callable

Inherits:
Object
  • Object
show all
Defined in:
lib/finite_machine/callable.rb

Overview

A generic interface for executing strings, symbol methods or procs.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object) ⇒ Callable

Initialize a Callable

Parameters:

  • object (Symbol, String, Proc)

    the callable object



15
16
17
# File 'lib/finite_machine/callable.rb', line 15

def initialize(object)
  @object = object
end

Instance Attribute Details

#objectObject (readonly)

Returns the value of attribute object.



7
8
9
# File 'lib/finite_machine/callable.rb', line 7

def object
  @object
end

Instance Method Details

#call(target, *args, &block) ⇒ Object

Execute action

Parameters:

  • target (Object)


31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/finite_machine/callable.rb', line 31

def call(target, *args, &block)
  case object
  when Symbol
    target.public_send(object.to_sym, *args, &block)
  when String
    string = args.empty? ? "-> { #{object} }" : "-> { #{object}(*#{args}) }"
    value  = eval(string)
    target.instance_exec(&value)
  when ::Proc
    object.arity.zero? ? object.call : object.call(target, *args)
  else
    raise ArgumentError, "Unknown callable #{object}"
  end
end

#invertObject

Invert callable



22
23
24
# File 'lib/finite_machine/callable.rb', line 22

def invert
  ->(*args, &block) { !call(*args, &block) }
end