Class: Waves::Matchers::Path

Inherits:
Object
  • Object
show all
Defined in:
lib/waves/matchers/path.rb

Instance Method Summary collapse

Constructor Details

#initialize(pattern) ⇒ Path

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

Empty Array means no path, but nil is not processed.



11
12
13
# File 'lib/waves/matchers/path.rb', line 11

def initialize(pattern)
  @pattern = pattern
end

Instance Method Details

#call(request) ⇒ Object

returns a hash of captured values



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
54
55
56
57
58
# File 'lib/waves/matchers/path.rb', line 16

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



63
64
65
# File 'lib/waves/matchers/path.rb', line 63

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