Class: MatchMethod
Overview
A MatchMethod a method that has a regular expression rather than a name. It simply stores a proc and the regular expression. To use:
mm = new MatchMethod(:matcher => /foo(w+)/, :proc => Proc.new {puts inspect})
fancy_object = Object.new
mm.match(fancy_object, :foobar)
=> <Object:0x1018746f8>
Instance Attribute Summary collapse
-
#matcher ⇒ Object
Returns the value of attribute matcher.
-
#proc ⇒ Object
Returns the value of attribute proc.
Instance Method Summary collapse
-
#initialize(args) ⇒ MatchMethod
constructor
Allows properties to be specified in the constructor.
-
#match(instance, message, *args) ⇒ Object
Calls the method’s
procon the giveninstance. -
#matches?(message) ⇒ Boolean
Returns whether this MatchMethod is capable of matching the given message.
Constructor Details
#initialize(args) ⇒ MatchMethod
Allows properties to be specified in the constructor. E.g.,
MatchMethod.new(:matcher => /foo/)
15 16 17 18 19 |
# File 'lib/match_method.rb', line 15 def initialize(args) args.each do |key, value| send("#{key}=", value) end end |
Instance Attribute Details
#matcher ⇒ Object
Returns the value of attribute matcher.
10 11 12 |
# File 'lib/match_method.rb', line 10 def matcher @matcher end |
#proc ⇒ Object
Returns the value of attribute proc.
10 11 12 |
# File 'lib/match_method.rb', line 10 def proc @proc end |
Instance Method Details
#match(instance, message, *args) ⇒ Object
Calls the method’s proc on the given instance.
28 29 30 31 32 33 34 35 36 37 |
# File 'lib/match_method.rb', line 28 def match(instance, , *args) groups = .to_s.match(matcher)[1..-1] # Should curry here: instance.instance_eval( &proc.curry(groups + args) ) # Or we could use instance_exec. # But these require 1.9. Darn. One day! full = (groups + args).flatten instance.instance_exec(*full, &proc) end |
#matches?(message) ⇒ Boolean
Returns whether this MatchMethod is capable of matching the given message.
23 24 25 |
# File 'lib/match_method.rb', line 23 def matches?() !!(.to_s =~ matcher) end |