class Filigree::MatchEnvironment
Match blocks are evaluated inside an instance of MatchEnvironment
.
Public Class Methods
# File lib/filigree/match.rb, line 229 def initialize @patterns = Array.new @deferred = Array.new end
Public Instance Methods
Force binding to the given name
@param [Symbol] name Name to bind the value to
@return [BindingPattern]
# File lib/filigree/match.rb, line 216 def Bind(name) BindingPattern.new(name) end
Force a literal comparison
@param [Object] obj Object
to test equality with
@return [LiteralPattern]
# File lib/filigree/match.rb, line 225 def Literal(obj) LiteralPattern.new(obj) end
Find a match for the given objects among the defined patterns.
@param [Array<Object>] objects Objects to be matched
@return [Object] Result of evaluating the matching pattern's block
@raise [MatchError] Raised if no pattern matches the objects
# File lib/filigree/match.rb, line 241 def find_match(objects) @patterns.each do |pattern| env = OpenStruct.new return pattern.(env, objects) if pattern.match?(objects, env) end # If we didn't find anything we raise a MatchError. raise MatchError end
Callback used to generate wildcard and binding patterns
# File lib/filigree/match.rb, line 282 def method_missing(name, *args) if args.empty? if name == :_ then WildcardPattern.instance else BindingPattern.new(name) end else super(name, *args) end end
Define a pattern in this match call.
@see match Documentation on pattern matching
@param [Object] pattern Objects defining the pattern @param [Proc] block Block to be executed if the pattern matches
@return [void]
# File lib/filigree/match.rb, line 260 def with(*pattern, &block) guard = if pattern.last.is_a?(Proc) then pattern.pop end pattern = Filigree::wrap_pattern_elements(pattern) @patterns << (mp = OuterPattern.new(pattern, guard, block)) if block @deferred.each { |deferred_pattern| deferred_pattern.block = block } @deferred.clear else @deferred << mp end end