Class: Filigree::MatchEnvironment

Inherits:
Object
  • Object
show all
Defined in:
lib/filigree/match.rb

Overview

Match blocks are evaluated inside an instance of MatchEnvironment.

Instance Method Summary collapse

Constructor Details

#initializeMatchEnvironment

Returns a new instance of MatchEnvironment.



231
232
233
234
# File 'lib/filigree/match.rb', line 231

def initialize
	@patterns = Array.new
	@deferred = Array.new
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object

Callback used to generate wildcard and binding patterns



284
285
286
287
288
289
290
# File 'lib/filigree/match.rb', line 284

def method_missing(name, *args)
	if args.empty?
		if name == :_ then WildcardPattern.instance else BindingPattern.new(name) end
	else
		super(name, *args)
	end
end

Instance Method Details

#Bind(name) ⇒ BindingPattern

Force binding to the given name

Parameters:

  • name (Symbol)

    Name to bind the value to

Returns:



218
219
220
# File 'lib/filigree/match.rb', line 218

def Bind(name)
	BindingPattern.new(name)
end

#find_match(objects) ⇒ Object

Find a match for the given objects among the defined patterns.

Parameters:

Returns:

  • (Object)

    Result of evaluating the matching pattern’s block

Raises:

  • (MatchError)

    Raised if no pattern matches the objects



243
244
245
246
247
248
249
250
251
252
# File 'lib/filigree/match.rb', line 243

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

#Literal(obj) ⇒ LiteralPattern

Force a literal comparison

Parameters:

  • obj (Object)

    Object to test equality with

Returns:



227
228
229
# File 'lib/filigree/match.rb', line 227

def Literal(obj)
	LiteralPattern.new(obj)
end

#with(*pattern, &block) ⇒ void Also known as: w

This method returns an undefined value.

Define a pattern in this match call.

Parameters:

  • pattern (Object)

    Objects defining the pattern

  • block (Proc)

    Block to be executed if the pattern matches

See Also:

  • Documentation on pattern matching


262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/filigree/match.rb', line 262

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 { |pattern| pattern.block = block }
		@deferred.clear

	else
		@deferred << mp
	end
end