Class: Filigree::DestructuringPattern

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

Overview

A pattern that matches an instance of a class and destructures it so that the values contained by the object may be matched upon.

Instance Attribute Summary collapse

Attributes inherited from MultipleObjectPattern

#pattern

Instance Method Summary collapse

Methods inherited from MultipleObjectPattern

#base_compare

Methods included from AbstractClass

#abstract_method, extended, #install_icvars, #new

Methods inherited from BasicPattern

#as

Constructor Details

#initialize(klass, pattern) ⇒ DestructuringPattern

Create a new destructuring pattern.

Parameters:

  • klass (Class)

    Class to match instances of. It must be destructurable.

  • pattern (Object)

    Pattern elements to use in matching the object’s values



597
598
599
600
# File 'lib/filigree/match.rb', line 597

def initialize(klass, pattern)
	@klass = klass
	super(pattern)
end

Instance Attribute Details

#klassClass (readonly)

Returns:



567
568
569
# File 'lib/filigree/match.rb', line 567

def klass
  @klass
end

Instance Method Details

#<=>(other) ⇒ Integer

Specialized version of the bi-directional comparison operator.

Parameters:

  • other (BasicPattern)

    Right-hand side of the comparison

Returns:

  • (Integer)

    Value corresponding to less than, equal to, or greater than the right-hand side pattern.



575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
# File 'lib/filigree/match.rb', line 575

def <=>(other)
	if other.is_a?(DestructuringPattern)
		if self.klass == other.klass
			base_compare(other) do
				self.pattern.zip(other.pattern).inject(0) do |total, pair|
					total + (pair.first <=> pair.last)
				end / self.pattern.length
			end

		elsif self.klass.subclass_of?(other.klass) then  1
		else                                            -1
		end

	else
		super
	end
end

#match?(object, env) ⇒ Boolean

Test to see if the object is an instance of the appropriate class, and if so destructure it and test it’s values against the sub-pattern elements.

Parameters:

  • object (Object)

    Object to test pattern against

  • env (Object)

    Binding environment

Returns:

  • (Boolean)


610
611
612
# File 'lib/filigree/match.rb', line 610

def match?(object, env)
	object.is_a?(@klass) and super(object.destructure(@pattern.length), env)
end

#weightObject



614
615
616
# File 'lib/filigree/match.rb', line 614

def weight
	1
end