Class: Rutter::Route

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

Overview

Represents a single route.

Constant Summary collapse

VERBS =

Valid request verbs.

%w[GET POST PUT PATCH DELETE OPTIONS HEAD TRACE].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#endpointHash (readonly)

Route endpoint.

Returns:

  • (Hash)

    the current value of endpoint



14
15
16
# File 'lib/rutter/route.rb', line 14

def endpoint
  @endpoint
end

#methodString (readonly)

Request method to match.

Returns:

  • (String)

    the current value of method



14
15
16
# File 'lib/rutter/route.rb', line 14

def method
  @method
end

#pathString (readonly)

Path to match.

Returns:

  • (String)

    the current value of path



14
15
16
# File 'lib/rutter/route.rb', line 14

def path
  @path
end

Instance Method Details

#expand(params = {}) ⇒ String

Expands the pattern with the given arguments.

Examples:

basic example

route = Route.new("GET", "/books/:id/:title", -> {})

route.expand(id: 54, title: "eloquent-ruby")
  # => "/books/54/eloquent-ruby"

with query

route = Route.new("GET", "/books/:id/reviews", -> {})

route.expand(id: 54, status: "approved")
  # => "/books/54/reviews?status=approved"

Parameters:

  • params (Hash) (defaults to: {})

    Expand parameters.

Returns:

  • (String)

    Expanded string.



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

def expand(params = {})
  string = if @dynamic
    new_path = path.gsub(SEGMENT_MATCH) do |match|
      params.delete(match[1..-1].to_sym)
    end
    new_path.gsub(/\(|\)/, "")
  else
    path.dup
  end

  string = normalize_path(string)
  return string if params.empty?

  "#{string}?#{Rack::Utils.build_nested_query(params)}"
end

#match?(path_info) ⇒ Boolean

Matches the given path to the route pattern.

Parameters:

  • path_info (String)

    Requested path to match against.

Returns:

  • (Boolean)


59
60
61
# File 'lib/rutter/route.rb', line 59

def match?(path_info)
  @dynamic ? path_info.match?(@pattern) : path_info == @path
end

#params(path) ⇒ nil, Hash<String => String>

Extract params from the given path.

NOTE: If the path does not match, nil is returned.

Parameters:

  • path (String)

    Requested path to extract params from.

Returns:

  • (nil, Hash<String => String>)


71
72
73
74
75
# File 'lib/rutter/route.rb', line 71

def params(path)
  return unless (result = path.match(@pattern))
  values = result.captures.map { |v| CGI.unescape(v) if v }
  Hash[result.names.zip(values)]
end