Sha256: e99157fbd670ab1c95386fac53f5d08c62808bcb576f6a454f5351d5d326833a

Contents?: true

Size: 1.03 KB

Versions: 19

Compression:

Stored size: 1.03 KB

Contents

# encoding: utf-8

module FiniteMachine
  # A generic interface for executing strings, symbol methods or procs.
  class Callable

    attr_reader :object

    # Initialize a Callable
    #
    # @param [Symbol, String, Proc] object
    #   the callable object
    #
    # @api public
    def initialize(object)
      @object = object
    end

    # Invert callable
    #
    # @api public
    def invert
      lambda { |*args, &block|  !call(*args, &block) }
    end

    # Execute action
    #
    # @param [Object] target
    #
    # @api public
    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
  end # Callable
end # FiniteMachine

Version data entries

19 entries across 19 versions & 1 rubygems

Version Path
finite_machine-0.11.3 lib/finite_machine/callable.rb
finite_machine-0.11.2 lib/finite_machine/callable.rb
finite_machine-0.11.1 lib/finite_machine/callable.rb
finite_machine-0.11.0 lib/finite_machine/callable.rb
finite_machine-0.10.2 lib/finite_machine/callable.rb
finite_machine-0.10.1 lib/finite_machine/callable.rb
finite_machine-0.10.0 lib/finite_machine/callable.rb
finite_machine-0.9.2 lib/finite_machine/callable.rb
finite_machine-0.9.1 lib/finite_machine/callable.rb
finite_machine-0.9.0 lib/finite_machine/callable.rb
finite_machine-0.8.1 lib/finite_machine/callable.rb
finite_machine-0.8.0 lib/finite_machine/callable.rb
finite_machine-0.7.1 lib/finite_machine/callable.rb
finite_machine-0.7.0 lib/finite_machine/callable.rb
finite_machine-0.6.1 lib/finite_machine/callable.rb
finite_machine-0.6.0 lib/finite_machine/callable.rb
finite_machine-0.5.0 lib/finite_machine/callable.rb
finite_machine-0.4.0 lib/finite_machine/callable.rb
finite_machine-0.3.0 lib/finite_machine/callable.rb