Class: MatchMethod

Inherits:
Object show all
Defined in:
lib/match_method.rb

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

Instance Method Summary collapse

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

#matcherObject

Returns the value of attribute matcher.



10
11
12
# File 'lib/match_method.rb', line 10

def matcher
  @matcher
end

#procObject

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, message, *args)
  groups = message.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.

Returns:

  • (Boolean)


23
24
25
# File 'lib/match_method.rb', line 23

def matches?(message)
  !!(message.to_s =~ matcher)
end