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.



229
230
231
232
# File 'lib/filigree/match.rb', line 229

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



282
283
284
285
286
287
288
# 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

Instance Method Details

#Bind(name) ⇒ BindingPattern

Force binding to the given name

Parameters:

  • name (Symbol)

    Name to bind the value to

Returns:



216
217
218
# File 'lib/filigree/match.rb', line 216

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

#find_match(objects) ⇒ Object

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

Parameters:

  • objects (Array<Object>)

    Objects to be matched

Returns:

  • (Object)

    Result of evaluating the matching pattern’s block

Raises:

  • (MatchError)

    Raised if no pattern matches the objects



241
242
243
244
245
246
247
248
249
250
# 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

#Literal(obj) ⇒ LiteralPattern

Force a literal comparison

Parameters:

  • obj (Object)

    Object to test equality with

Returns:



225
226
227
# File 'lib/filigree/match.rb', line 225

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


260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# 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