Module: Matchete::ClassMethods
- Defined in:
- lib/matchete.rb
Instance Method Summary collapse
- #convert_to_matcher(function) ⇒ Object
- #default(method_name) ⇒ Object
- #duck(*method_names) ⇒ Object
- #match_guard(guard, arg) ⇒ Object
- #match_guards(guards, args) ⇒ Object
- #on(*guards, function) ⇒ Object
Instance Method Details
#convert_to_matcher(function) ⇒ Object
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/matchete.rb', line 36 def convert_to_matcher(function) define_method(function) do |*args| guards = self.class.instance_variable_get('@functions')[function].find do |guards, _| self.class.match_guards guards, args end handler = if guards.nil? default_method = self.class.instance_variable_get('@default_functions')[function] if default_method default_method else raise NotResolvedError.new("not resolved #{function} with #{args}") end else guards[1] end handler.bind(self).call *args end end |
#default(method_name) ⇒ Object
23 24 25 26 |
# File 'lib/matchete.rb', line 23 def default(method_name) @default_functions[method_name] = instance_method(method_name) convert_to_matcher method_name end |
#duck(*method_names) ⇒ Object
28 29 30 31 32 33 34 |
# File 'lib/matchete.rb', line 28 def duck(*method_names) -> object do method_names.all? do |method_name| object.respond_to? method_name end end end |
#match_guard(guard, arg) ⇒ Object
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
# File 'lib/matchete.rb', line 63 def match_guard(guard, arg) case guard when Module arg.is_a? guard when Symbol send guard, arg when Proc guard.call arg when String guard == arg when Regexp arg.is_a? String and guard.match arg when Array arg.is_a?(Array) and guard.zip(arg).all? { |child_guard, child| match_guard child_guard, child } else guard == arg end end |
#match_guards(guards, args) ⇒ Object
57 58 59 60 61 |
# File 'lib/matchete.rb', line 57 def match_guards(guards, args) guards.zip(args).all? do |guard, arg| match_guard guard, arg end end |
#on(*guards, function) ⇒ Object
17 18 19 20 21 |
# File 'lib/matchete.rb', line 17 def on(*guards, function) @functions[function] ||= [] @functions[function] << [guards, instance_method(function)] convert_to_matcher function end |