Class: Waves::Matchers::Path

Inherits:
Base show all
Defined in:
lib/matchers/path.rb

Instance Attribute Summary

Attributes inherited from Base

#constraints

Instance Method Summary collapse

Methods inherited from Base

#[], #test

Constructor Details

#initialize(pattern) ⇒ Path

Takes an array of pattern elements … coming soon, support for formatted strings!



8
# File 'lib/matchers/path.rb', line 8

def initialize( pattern ) ; @pattern = pattern  ; end

Instance Method Details

#call(request) ⇒ Object

returns a hash of captured values



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/matchers/path.rb', line 11

def call( request )
  if @pattern.is_a? Array
    path = extract_path( request ).reverse
    return {} if @pattern.empty? && path.empty?
    capture = {}
    match = @pattern.all? do | want |
      case want
      when true # same as a Range of 1..-1
        path = [] unless path.empty?
      when Range 
        if want.end == -1
          path = [] if path.length >= want.begin
        else
          path = [] if want.include? path.length
        end
      when String then want == path.pop
      when Symbol then capture[ want ] = path.pop
      when Regexp then want === path.pop
      when Hash
        key, value = want.to_a.first
        case value
        when true
          ( capture[ key ], path = path.reverse, [] ) unless path.empty?
        when Range
          if value.end == -1
            ( capture[ key ], path = path.reverse, [] ) if path.length >= value.begin
          else
            ( capture[ key ], path = path.reverse, [] ) if value.include? path.length
          end
        when String, Symbol
          got = path.pop
          capture[ key ] = got ? got : value.to_s
        when Regexp then
          got = path.pop
          capture[ key ] = got if value === got
        end
      end
    end
    capture if match && path.empty?
  elsif @pattern == true or @pattern == false or @pattern == nil
    {}
  end
end

#extract_path(request) ⇒ Object

just a little helper method



58
59
60
# File 'lib/matchers/path.rb', line 58

def extract_path( request )
  request.traits.waves.path ||= request.path.scan(/[^\/]+/).map { |e| Rack::Utils.unescape(e) }
end