Class: StringBasedRouting

Inherits:
Object
  • Object
show all
Defined in:
lib/routing/utils/string_based_routing.rb

Overview

Base class for rack-compatible string-based Routing

Used to define routes such as /posts, /posts/:index, and /posts/:index/edit

Direct Known Subclasses

HanamiRouting, SinatraRouting

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeStringBasedRouting

Returns a new instance of StringBasedRouting.



8
9
10
# File 'lib/routing/utils/string_based_routing.rb', line 8

def initialize
  @params = {}
end

Class Method Details

.routesObject



13
14
15
# File 'lib/routing/utils/string_based_routing.rb', line 13

def routes
  @routes ||= []
end

Instance Method Details

#call(env) ⇒ Object



48
49
50
51
52
53
54
55
56
57
# File 'lib/routing/utils/string_based_routing.rb', line 48

def call(env)
  route = self.class.routes.find do |route|
    route[:method] == env['REQUEST_METHOD'] and route[:pattern] =~ env['PATH_INFO']
  end

  return not_found('404 Not Found') unless route

  set_params!(Regexp.last_match.named_captures)
  execute_route(route)
end

#html(doc) ⇒ Object



29
30
31
# File 'lib/routing/utils/string_based_routing.rb', line 29

def html(doc)
  [200, { 'content-type' => 'text/html' }, [doc]]
end

#not_found(doc) ⇒ Object



33
34
35
# File 'lib/routing/utils/string_based_routing.rb', line 33

def not_found(doc)
  [404, { 'content-type' => 'text/html' }, [doc]]
end

#set_params!(named_captures) ⇒ Object

Declare params as a hash from symbol => value Then expose it as a singleton_method for calling the route’s block



40
41
42
43
44
45
46
# File 'lib/routing/utils/string_based_routing.rb', line 40

def set_params!(named_captures)
  params = {}
  named_captures&.each do |name, value|
    params[name.to_sym] = value
  end
  define_singleton_method('params', -> { params })
end