Class: Rack::Router::RouteBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/router/route_builder.rb

Instance Method Summary collapse

Constructor Details

#initializeRouteBuilder

Returns a new instance of RouteBuilder.



4
5
6
# File 'lib/rack/router/route_builder.rb', line 4

def initialize
  @routes = []
end

Instance Method Details

#add(http_method, path, value, options = {}) ⇒ Object

Parameters:

  • http_method (Symbol, String)
  • path (String)
  • value (String, Proc<Hash>)
  • options (Hash) (defaults to: {})

    :constraint [Hash<Symbol,Proc<String>>] :content_type [Array<String>,String]



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/rack/router/route_builder.rb', line 14

def add(http_method, path, value, options = {})
  path = path.split('/').reject(&:empty?).join('/')
  route = Route.new(
      http_method: http_method.to_s.upcase,
      path: path,
      value: value,
      **options
  )
  @routes.push(route)
  route
end

#match(env) ⇒ Object



26
27
28
29
30
31
32
33
34
35
# File 'lib/rack/router/route_builder.rb', line 26

def match(env)
  http_method = env[Rack::REQUEST_METHOD]
  path = env[Rack::PATH_INFO].to_s.gsub(/\..*\z/, '')
  content_type, *_ = env['CONTENT_TYPE'].to_s.split(';')
  content_type = nil if !content_type.nil? && content_type.empty?
  accept, *_ = env['HTTP_ACCEPT'].to_s.split(';')
  accept = accept.to_s.split(',')

  match_request(http_method, path, content_type: content_type, accept: accept)
end

#match_request(http_method, path, content_type: nil, accept: []) ⇒ Object

Parameters:

  • http_method (String)

    upcase GET POST PUT PATCH DELETE HEAD

  • path (String)
  • content_type (String, NilClass) (defaults to: nil)
  • accept (Array) (defaults to: [])


41
42
43
44
45
46
47
48
49
50
51
# File 'lib/rack/router/route_builder.rb', line 41

def match_request(http_method, path, content_type: nil, accept: [])
  path_parts = path.split('/').reject(&:empty?)
  @routes.detect do |route|
    next false if route.http_method && route.http_method != http_method
    next false if route.content_type && route.content_type.include?(content_type)
    next false if route.accept && (route.accept & accept).empty? && !accept.include?('*/*')
    next false if route.path_parts.size != path_parts.size
    next false if route.path_parts.map.with_index { |part, idx| part != path_parts[idx] }.any?
    true
  end
end


53
54
55
# File 'lib/rack/router/route_builder.rb', line 53

def print_routes
  "Routes (#{@routes.size}):\n" + @routes.map(&:print_route).join("\n") + "\n"
end