Class: PatternProc::PatternProcCase

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args, previous_specificity = 0, proc_arity = 0, &block) ⇒ PatternProcCase

Returns a new instance of PatternProcCase.



81
82
83
84
85
86
87
88
89
# File 'lib/pattern_proc.rb', line 81

def initialize(args, previous_specificity = 0, proc_arity = 0, &block)
  @expected_args = args
  @proc = block
  @proc_arity = proc_arity
  @previous_specificity = previous_specificity || 0
  if !block.nil? && block.arity > 0
    @proc_arity = block.arity
  end
end

Instance Attribute Details

#proc_applied_levelObject (readonly)

Returns the value of attribute proc_applied_level.



78
79
80
# File 'lib/pattern_proc.rb', line 78

def proc_applied_level
  @proc_applied_level
end

#proc_arityObject (readonly)

Returns the value of attribute proc_arity.



79
80
81
# File 'lib/pattern_proc.rb', line 79

def proc_arity
  @proc_arity
end

Instance Method Details

#arityObject



101
102
103
# File 'lib/pattern_proc.rb', line 101

def arity
  expected_arity + proc_arity
end

#expected_arityObject

private ish



97
98
99
# File 'lib/pattern_proc.rb', line 97

def expected_arity
  @expected_args.size || 0
end

#make_subcase(args) ⇒ Object



109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/pattern_proc.rb', line 109

def make_subcase(args)
  match_len = [args.size, @expected_args.size].min
  expected = @expected_args.take(match_len)
  actual = args.take(match_len)
  if expected == actual
    new_proc = to_proc.curry
    curry_count = args.size - @expected_args.size
    new_arity = proc_arity
    if curry_count > 0
      send_args = args.drop(match_len).take(curry_count)
      new_proc = new_proc.call(*send_args)
      new_arity -= curry_count
      if new_arity == 0
        return PatternProcCase.new([], specificity).returns(new_proc)
      elsif !(new_proc.is_a?(Proc))
        raise "uh oh"
      end
    end
    PatternProcCase.new(@expected_args.drop(match_len), specificity, new_arity, &new_proc).returns(@return_value)
  else
    nil
  end
end

#returns(value) ⇒ Object



91
92
93
94
# File 'lib/pattern_proc.rb', line 91

def returns(value)
  @return_value = value
  self
end

#specificityObject



105
106
107
# File 'lib/pattern_proc.rb', line 105

def specificity
  expected_arity + @previous_specificity
end

#to_procObject



133
134
135
# File 'lib/pattern_proc.rb', line 133

def to_proc
  @proc || ->(*args) { @return_value }
end