Module: Invokable::Closure::ClassMethods

Defined in:
lib/invokable/closure.rb

Instance Method Summary collapse

Instance Method Details

#arityInteger

Return the “total” arity of the class (i.e. the arity of the initializer and the arity of the call method)

Returns:

  • (Integer)

See Also:

Version:

  • 0.5.0



23
24
25
# File 'lib/invokable/closure.rb', line 23

def arity
  initializer_arity + instance_method(:call).arity
end

#call(*args) ⇒ Object

Handle automatic currying–will accept either the initializer arity or the total arity of the class. If the initializer arity is used return a class instance. If the total arity is used instantiate the class and return the results of the ‘call` method.

See Also:

Version:

  • 0.5.0



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/invokable/closure.rb', line 44

def call(*args)
  if args.length == initializer_arity
    new(*args)
  elsif args.length == arity
    init_args = args.slice(0, initializer_arity)
    call_args = args.slice(initializer_arity, args.length)
    new(*init_args).call(*call_args)
  else
    raise ArgumentError, "wrong number of arguments (given #{args.length}, expected #{initializer_arity} or #{arity})"
  end
end

#enclose(*names, &block) ⇒ Object

Specify any enclosed state with a block or named attributes

Examples:

class TwitterPater
  include Invokable::Command

  enclose :api_key

  def call(user)
    # interact with twitter, return results
  end
end

TwitterPater.new(API_KEY).call(User.find(1))
TwitterPater.new(API_KEY).api_key == API_KEY # => true

class TwitterPater
  include Invokable::Command

  enclose do |api_key|
    @api_key = api_key
  end

  def call(user)
    # interact with twitter, return results
  end
end

TwitterPater.new(API_KEY).call(User.find(1))
TwitterPater.new(API_KEY).api_key # error 'method' missing


86
87
88
89
90
# File 'lib/invokable/closure.rb', line 86

def enclose(*names, &block)
  return define_initializer_with_block(block) unless block.nil?

  define_initializer_with_names(names)
end

#initializer_arityInteger

Return the arity of the initializer

Returns:

  • (Integer)

See Also:

Version:

  • 0.5.0



33
34
35
# File 'lib/invokable/closure.rb', line 33

def initializer_arity
  instance_method(:initialize).arity
end