Module: Invokable::ClassMethods

Defined in:
lib/invokable.rb

Overview

Note:

The module should not be used directly.

The methods that are mixed into any class at the class level that includes Invokable.

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)

Version:

  • 0.6.0



55
56
57
58
59
# File 'lib/invokable.rb', line 55

def arity
  return initializer_arity + invoker_arity if invoker_arity >= 0

  (initializer_arity + invoker_arity.abs) * -1
end

#call(*args, **kwargs) ⇒ 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.

Raises:

  • (ArgumentError)

See Also:

Version:

  • 0.6.0



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/invokable.rb', line 68

def call(*args, **kwargs)
  initializer = initializer_arity
  raise ArgumentError, "variable length initializer methods are not supported by Invokable try using `new' or `curry' instead" if initializer < 0
  raise ArgumentError, "block arguments are not supported by Invokable" if block_given?
  
  return new.call if arity.zero?
  
  argc    = kwargs.empty? ? args.length : args.length + 1
  invoker = invoker_arity
  return new(*args).call           if argc == initializer && invoker.zero? && kwargs.empty?
  return new(*args, **kwargs).call if argc == initializer && invoker.zero?
  return new(*args).call           if argc == initializer && invoker == -1 && kwargs.empty?
  return new(*args).call(**kwargs) if argc == initializer && invoker == -1
  return new(*args)                if argc == initializer && kwargs.empty?
  return new(*args, **kwargs)      if argc == initializer

  if argc == arity || invoker_arity < 0 && (args.length - initializer) >= (invoker.abs - 1)
    init_args = args.slice(0, initializer)
    call_args = args.slice(initializer, args.length)
    return new(*init_args).call(*call_args) if kwargs.empty?
    return new(*init_args).call(*call_args, **kwargs)
  else
    raise ArgumentError, "wrong number of arguments (given #{args.length}, expected #{arity})" if initializer == arity
    raise ArgumentError, "wrong number of arguments (given #{args.length}, expected #{initializer} or #{arity})"
  end
end

#initializer_arityObject



95
96
97
# File 'lib/invokable.rb', line 95

def initializer_arity
  instance_method(:initialize).arity
end

#invoker_arityObject



99
100
101
# File 'lib/invokable.rb', line 99

def invoker_arity
  instance_method(:call).arity
end