class Truss::Router::Node

Attributes

allowed_methods[RW]
endpoint[RW]
has_dynamic_segments[RW]
matchable_regex[RW]
options[RW]
path[RW]
path_segments[RW]
request_method[RW]

Public Class Methods

new(method, path, endpoint, options={}) click to toggle source
# File lib/truss/router/node.rb, line 8
def initialize(method, path, endpoint, options={})
    @request_method, @path, @endpoint = method, path, endpoint
    @has_dynamic_segments = false
    @matchable_regex = build_matchable_regex(method, path, options)
    @allowed_methods = discover_allowed_methods(method, path, options)
    @path_segments   = get_path_segments(path)
    @options = options
end

Public Instance Methods

call(request) click to toggle source
# File lib/truss/router/node.rb, line 29
def call request
    endpoint.call(request)
end
matches?(request) click to toggle source
# File lib/truss/router/node.rb, line 17
def matches? request
    if has_dynamic_segments
        match = matchable_regex.match(request.routing_path)
        if match
            request.routing_params = Hash[match.names.zip(match.captures)]
        end
        match
    else
        matchable_regex.match(request.routing_path)
    end
end

Private Instance Methods

build_matchable_regex(method, path, options) click to toggle source
# File lib/truss/router/node.rb, line 34
def build_matchable_regex(method, path, options)
    if path.include?(":")
        self.has_dynamic_segments = true
        /\A#{segment_string(path)}\Z/
    else
        %r[\A#{path}\Z]
    end
end
discover_allowed_methods(method, path, options) click to toggle source
# File lib/truss/router/node.rb, line 43
def discover_allowed_methods(method, path, options)
    allowed = [method.to_s.upcase]
    allowed << "OPTIONS" if options.has_key?(:cors)
    allowed << "HEAD" if (method == :get)
    allowed
end
get_path_segments(path) click to toggle source
# File lib/truss/router/node.rb, line 50
def get_path_segments(path)
    path.split("/").reject(&:empty?).count
end
segment_string(path) click to toggle source
# File lib/truss/router/node.rb, line 54
def segment_string(path)
    components = path.split("/").map do |comp|
        if comp[0] == ":"
            "(?<#{comp[1..-1]}>[\\w\\-]+)"
        else
            comp
        end
    end
    "#{components.join('/')}"
end