Module: Matchete::ClassMethods
- Defined in:
- lib/matchete.rb
Instance Method Summary collapse
- #convert_to_matcher(method_name) ⇒ Object
- #default(method_name) ⇒ Object
-
#either(*guards) ⇒ Object
Matches something like sum types: either(Integer, Array) matches both [2] and 2.
-
#exact(value) ⇒ Object
Matches an exact value useful if you want to match a string starting with ‘#’ or the value of a class exact(Integer) matches Integer, not 2.
-
#full_match(*guards) ⇒ Object
Matches each guard full_match(Integer, ‘#value’) matches only instances of Integer which respond to ‘#value’.
-
#having(**properties) ⇒ Object
Matches property results e.g.
- #on(*args, **kwargs) ⇒ Object
- #supporting(*method_names) ⇒ Object
Instance Method Details
#convert_to_matcher(method_name) ⇒ Object
72 73 74 75 76 |
# File 'lib/matchete.rb', line 72 def convert_to_matcher(method_name) define_method(method_name) do |*args, **kwargs| call_overloaded(method_name, args: args, kwargs: kwargs) end end |
#default(method_name) ⇒ Object
30 31 32 33 |
# File 'lib/matchete.rb', line 30 def default(method_name) @default_methods[method_name] = instance_method(method_name) convert_to_matcher method_name end |
#either(*guards) ⇒ Object
Matches something like sum types: either(Integer, Array) matches both [2] and 2
38 39 40 |
# File 'lib/matchete.rb', line 38 def either(*guards) -> arg { guards.any? { |g| match_guard(g, arg) } } end |
#exact(value) ⇒ Object
Matches an exact value useful if you want to match a string starting with ‘#’ or the value of a class exact(Integer) matches Integer, not 2
45 46 47 |
# File 'lib/matchete.rb', line 45 def exact(value) -> arg { arg == value } end |
#full_match(*guards) ⇒ Object
Matches each guard full_match(Integer, ‘#value’) matches only instances of Integer which respond to ‘#value’
60 61 62 |
# File 'lib/matchete.rb', line 60 def full_match(*guards) -> arg { guards.all? { |g| match_guard(g, arg) } } end |
#having(**properties) ⇒ Object
Matches property results e.g. having(‘#to_s’: ‘[]’) will match []
51 52 53 54 55 |
# File 'lib/matchete.rb', line 51 def having(**properties) -> arg do properties.all? { |prop, result| arg.respond_to?(prop[1..-1]) && arg.send(prop[1..-1]) == result } end end |
#on(*args, **kwargs) ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/matchete.rb', line 15 def on(*args, **kwargs) if kwargs.count.zero? *guard_args, method_name = args guard_kwargs = {} else method_name = kwargs[:method] kwargs.delete :method guard_args = args guard_kwargs = kwargs end @methods[method_name] ||= [] @methods[method_name] << [guard_args, guard_kwargs, instance_method(method_name)] convert_to_matcher method_name end |
#supporting(*method_names) ⇒ Object
64 65 66 67 68 69 70 |
# File 'lib/matchete.rb', line 64 def supporting(*method_names) -> object do method_names.all? do |method_name| object.respond_to? method_name end end end |