Class: Serega::SeregaUtils::MethodSignature

Inherits:
Object
  • Object
show all
Defined in:
lib/serega/utils/method_signature.rb

Overview

Utility to make method arguments signature

Class Method Summary collapse

Class Method Details

.call(callable, pos_limit:, keyword_args: []) ⇒ String

Generates method arguments signature

Parameters:

  • callable (#call)

    callable object

  • pos_limit (Integer)

    Max count of positional parameters

  • keyword_args (Array<Symbol>) (defaults to: [])

    List of accepted keyword argument names

Returns:

  • (String)

    Method signature which consist of number of positional parameters and keyword parameter names joined with undescrore.



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/serega/utils/method_signature.rb', line 28

def call(callable, pos_limit:, keyword_args: [])
  params = callable.is_a?(Proc) ? callable.parameters : callable.method(:call).parameters

  # Procs (but not lambdas) can accept all provided parameters
  return full_signature(pos_limit, keyword_args) if params.empty? && callable.is_a?(Proc) && !callable.lambda?

  # Return single positional argument for Symbol#to_proc
  return "1" if (params == SYMBOL_TO_PROC_SIGNATURE_RUBY2) || (params == SYMBOL_TO_PROC_SIGNATURE_RUBY3)

  keyword_args = keyword_args.dup

  # signature parts
  positional_parameters = 0
  keyword_parameters = []

  params.each do |type, name|
    case type
    when :req, :opt
      positional_parameters += 1
      pos_limit -= 1
    when :rest
      next if pos_limit <= 0

      positional_parameters += pos_limit
      pos_limit = 0
    when :key, :keyreq
      keyword_parameters << name
      keyword_args.delete(name)
    when :keyrest
      keyword_parameters.concat(keyword_args)
      keyword_args.clear
    end
  end

  build_signature_string(positional_parameters, keyword_parameters)
end