Class: Exo::PathMatcher
- Inherits:
-
Object
- Object
- Exo::PathMatcher
- Defined in:
- app/services/exo/path_matcher.rb
Instance Attribute Summary collapse
-
#keys ⇒ Object
Returns the value of attribute keys.
-
#regexp ⇒ Object
Returns the value of attribute regexp.
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(path_pattern) ⇒ PathMatcher
constructor
A new instance of PathMatcher.
- #match?(path, params = nil) ⇒ Boolean
Constructor Details
#initialize(path_pattern) ⇒ PathMatcher
Returns a new instance of PathMatcher.
35 36 37 38 39 40 41 42 43 |
# File 'app/services/exo/path_matcher.rb', line 35 def initialize path_pattern self.keys = [] regpath = path_pattern.gsub(/:([^\/]+)/) do |match| key = $1 keys.push key.to_sym "(?<#{key}>.+)" end self.regexp = /\A#{regpath}\z/i end |
Instance Attribute Details
#keys ⇒ Object
Returns the value of attribute keys.
21 22 23 |
# File 'app/services/exo/path_matcher.rb', line 21 def keys @keys end |
#regexp ⇒ Object
Returns the value of attribute regexp.
21 22 23 |
# File 'app/services/exo/path_matcher.rb', line 21 def regexp @regexp end |
Class Method Details
.route_for(routes, params, key = :route_path, &builder) ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'app/services/exo/path_matcher.rb', line 22 def self.route_for routes, params, key=:route_path, &builder path = params[key] raise "Params does not countain any path" unless path path = "/#{path}" unless path[0] == '/' routes.each do |route| if new(route.path).match? path, params builder.call route break end end end |
.test ⇒ Object
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# File 'app/services/exo/path_matcher.rb', line 3 def self.test raise '1' unless new('/home').match?('/home') hash = {} raise '2' unless new('/home/:test').match?('/home/a', hash) raise '3' unless hash[:test] == 'a' hash = {} raise '4' unless new('/home/:test/another/:lol').match?('/home/abc/another/def', hash) raise '5' unless hash[:test] == 'abc' raise '6' unless hash[:lol] == 'def' hash = {} raise '7' unless new('/home/:test/another/:lol/fun').match?('/home/abc/another/def/fun', hash) raise '8' unless hash[:test] == 'abc' raise '9' unless hash[:lol] == 'def' end |
Instance Method Details
#match?(path, params = nil) ⇒ Boolean
45 46 47 48 49 50 51 52 53 |
# File 'app/services/exo/path_matcher.rb', line 45 def match? path, params=nil matching = regexp.match path if matching && params keys.each do |k| params[k] = matching[k] end end !!matching end |