Module: KeywordCurry::KeywordArgumentCurrying

Defined in:
lib/keyword_curry/keyword_argument_currying.rb

Instance Method Summary collapse

Instance Method Details

#curry(arity = arity) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
# File 'lib/keyword_curry/keyword_argument_currying.rb', line 2

def curry(arity = arity)
  required_keywords = parameters
    .select { |param| param.first == :keyreq }
    .map    { |param| param.last }

  if required_keywords.empty?
    super
  else
    curried_proc = self
    collected_positional_args = []
    collected_keyword_args = {}

    keyword_currier = Proc.new { |keywords|
      curried_proc.call(keywords) unless keywords.is_a?(Hash)

      collected_keyword_args.merge!(keywords)

      outstanding_keywords = required_keywords - collected_keyword_args.keys

      if outstanding_keywords.empty?
        curried_proc.call(*collected_positional_args, collected_keyword_args)
      else
        keyword_currier
      end
    }

    positional_argument_handler = Proc.new { |*args|
      if arity == -1
        keyword_args = args.last if args.last.is_a?(Hash)

        if keyword_args
          positional_args = args[0..-2]
        else
          positional_args = args
          keyword_args = {}
        end
      else
        positional_args = args.take(curried_proc.arity)
        keyword_args = args[curried_proc.arity..-1].first || {}
      end

      collected_positional_args += positional_args
      keyword_currier.call(keyword_args)
    }

    if arity == 0
      keyword_currier
    else
      positional_argument_handler.curry(arity)
    end
  end
end