Class: Utopia::Path::Matcher

Inherits:
Object
  • Object
show all
Defined in:
lib/utopia/path/matcher.rb

Defined Under Namespace

Classes: MatchData

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(patterns = []) ⇒ Matcher

patterns = {key: /d+/, ‘foo’, }



45
46
47
# File 'lib/utopia/path/matcher.rb', line 45

def initialize(patterns = [])
	@patterns = patterns
end

Class Method Details

.[](patterns) ⇒ Object



49
50
51
# File 'lib/utopia/path/matcher.rb', line 49

def self.[](patterns)
	self.new(patterns)
end

Instance Method Details

#coerce(klass, value) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
# File 'lib/utopia/path/matcher.rb', line 53

def coerce(klass, value)
	if klass == Integer
		Integer(value) rescue nil
	elsif klass == Float
		Float(value) rescue nil
	elsif klass == String
		value.to_s
	else
		klass.new(value)
	end
end

#match(path) ⇒ Object

This is a path prefix matching algorithm. The pattern is an array of String, Symbol, Regexp, or nil. The components is an array of String. As long as the components match the patterns,



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/utopia/path/matcher.rb', line 67

def match(path)
	components = path.to_a
	
	return nil if components.size < @patterns.size
	
	named_parts = {}
	
	@patterns.each_with_index do |(key, matcher), index|
		component = components[index]
		
		if matcher.is_a? Class
			return nil unless value = coerce(matcher, component)
			
			named_parts[key] = value
		elsif matcher
			return nil unless matcher === component
			
			named_parts[key] = component
		else
			named_parts[key] = component
		end
	end
	
	return MatchData.new(named_parts, components[@patterns.size..-1])
end