lib/patternmatching/pattern.rb in patternmatching-0.2.1 vs lib/patternmatching/pattern.rb in patternmatching-0.2.2
- old
+ new
@@ -105,22 +105,26 @@
end
#Private class to run pattern matching
class MatchExec
def self.exec_as(target, patterns, receiver)
- patterns.each do |pair|
- pattern = pair.keys[0]
- action = pair[pattern]
+ patterns.each do |tuple|
+ pattern = tuple[0]
+ action = tuple[1]
+ condition = tuple[2]
source = NodeBuilder.new.instance_eval(&pattern)
args = {}
begin
Collector.walk(source, target, args)
rescue NotMatched
next
end
- return ExecuteAs.new(args, receiver).instance_eval(&action)
- end
+ executer = ExecuteAs.new(args, receiver)
+ next if condition != nil and not executer.instance_eval(&condition)
+ return executer.instance_eval(&action)
+ end
+ nil
end
# Private class to access instance valiables of the receiver
class InstanceVariableAccessor
def initialize(receiver)
@@ -165,17 +169,20 @@
#Private class for collecting pattern/action fragments
class PatternFragments
def initialize(patterns)
@patterns = patterns
end
- def seems(pattern, &action)
- @patterns << {pattern => action}
+ def seems(pattern, condition = nil, &action)
+ @patterns << [pattern, action, condition]
self
end
def as(&block)
block
end
+ def with(&block)
+ block
+ end
def something
proc {_}
end
end
@@ -210,9 +217,16 @@
#A pattern matches description inside block
#=== Usage
# seems as {some pattern...} do ... end
def as(&block)
+ block
+ end
+
+ #A pattern restriction, must boolean
+ #=== Usage
+ # seems as {PATTERN}, with {CONDITION} do ... end
+ def with(&block)
block
end
#A pattern matches anything
#=== Usage