Class: RouterSimple::Route

Inherits:
Object
  • Object
show all
Defined in:
lib/router_simple.rb

Overview

Route class

Instance Method Summary collapse

Constructor Details

#initialize(http_method, path, dest) ⇒ Route

Create new route object

Parameters:

  • http_method (Araray or String or NilClass)

    HTTP method. You can specify nil, [‘GET’, ‘HEAD“], ’GET’, etc.

  • path (String)
  • dest (Any)

    Destination of this path



79
80
81
82
83
84
# File 'lib/router_simple.rb', line 79

def initialize(http_method, path, dest)
    @path = path
    @pattern = compile(path)
    @dest = dest
    @http_method = http_method.is_a?(String) ? [http_method] : http_method
end

Instance Method Details

#compile(path) ⇒ Object

compile ‘path’ pattern to regexp.



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/router_simple.rb', line 111

def compile(path)
    if path.kind_of?(Regexp)
        return path
    else
        pattern = Regexp.compile(
            '\A' + (
            path.gsub(/[-\[\]{}()+?.,\\^$|#\s]/) {|x|
                Regexp.escape(x)
            }
            .gsub(/:([\w\d]+)/, "(?<\\1>[^\/]+)")
            .gsub(/\*([\w\d]+)/, "(?<\\1>.+?)")
            ) + '\z'
        )
        pattern
    end
end

#match(http_method, path) ⇒ Object

Match to this route

Parameters:

  • http_method (String)

    REQUEST_METHOD

  • path (String or Regexp)

    PATH_INFO

Returns:

  • dest Destination for this route

  • captures captured parameters by router

  • method_not_allowed True if the route was denied by method.



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/router_simple.rb', line 94

def match(http_method, path)
    matched = @pattern.match(path)
    if matched
        if @http_method && !@http_method.any? {|m| m==http_method}
            return nil, nil, true
        end
        captures = {}
        matched.names.zip(matched.captures).each {|x|
            captures[x[0]] = x[1]
        }
        return @dest, captures
    else
        return nil, nil
    end
end