Class: Arity::Function

Inherits:
Object
  • Object
show all
Defined in:
lib/arity/function.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(fn) ⇒ Function

Returns a new instance of Function.



14
15
16
# File 'lib/arity/function.rb', line 14

def initialize(fn)
  @callable = unwrap_function(fn)
end

Instance Attribute Details

#callableObject (readonly)

Returns the value of attribute callable.



4
5
6
# File 'lib/arity/function.rb', line 4

def callable
  @callable
end

Class Method Details

.make(fn, silent: false) ⇒ Object

Raises:



8
9
10
11
12
# File 'lib/arity/function.rb', line 8

def self.make(fn, silent: false)
  return new(fn) if fn.respond_to?(:call)
  return if silent
  raise NotCallableError, "function is not callable: #{fn.inspect}"
end

Instance Method Details

#arityObject



18
19
20
# File 'lib/arity/function.rb', line 18

def arity
  callable.arity
end

#run(*args, **opts) ⇒ Object



50
51
52
53
# File 'lib/arity/function.rb', line 50

def run(*args, **opts)
  args.push(opts) unless opts.empty?
  callable.call(*args)
end

#runnable?(*args, **opts) ⇒ Boolean

Returns:

  • (Boolean)


46
47
48
# File 'lib/arity/function.rb', line 46

def runnable?(*args, **opts)
  takes?(arg_count: args.size, keywords: opts.keys)
end

#signatureObject



22
23
24
# File 'lib/arity/function.rb', line 22

def signature
  @signature ||= compute_signature
end

#takes?(arg_count:, keywords:) ⇒ Boolean

Returns:

  • (Boolean)


26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/arity/function.rb', line 26

def takes?(arg_count:, keywords:)
  bad_param('arg_count', 'an int', arg_count) if !arg_count.is_a?(Integer)
  bad_param('keywords', 'an array', keywords) if !keywords.is_a?(Array)

  return false if arg_count < signature[:min_args]

  if signature[:max_args] > -1
    return false if arg_count > signature[:max_args]
  end

  missing = signature[:required_keys] - keywords
  return false if !missing.empty?

  return true if signature[:any_key]

  extra_keys = keywords - signature[:required_keys] \
                        - signature[:optional_keys]
  extra_keys.empty?
end