Class: WhalesDispatch::Router

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

Constant Summary collapse

HTML_METHODS =
[:get, :post, :patch, :put, :delete]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeRouter

Returns a new instance of Router.



7
8
9
10
# File 'lib/whales_dispatch/router.rb', line 7

def initialize
  @routes = []
  # @last_parent_route = ""
end

Instance Attribute Details

#routesObject (readonly)

Returns the value of attribute routes.



5
6
7
# File 'lib/whales_dispatch/router.rb', line 5

def routes
  @routes
end

Instance Method Details

#add_route(pattern, method, controller_class, action_name) ⇒ Object



12
13
14
# File 'lib/whales_dispatch/router.rb', line 12

def add_route(pattern, method, controller_class, action_name)
  @routes << Route.new(pattern, method, controller_class, action_name)
end

#build_resources(controller_noun, controller_actions) ⇒ Object



32
33
34
35
36
37
38
39
40
41
# File 'lib/whales_dispatch/router.rb', line 32

def build_resources(controller_noun, controller_actions)
  controller_actions.actions.each do |action_name, action_hash|

    resource = Resource.new(
      controller_noun, action_hash[:suffix], @last_parent_route
    )

    send action_hash[:method], resource.pattern, resource.classify, action_name
  end
end

#draw(&proc) ⇒ Object



16
17
18
# File 'lib/whales_dispatch/router.rb', line 16

def draw(&proc)
  instance_eval(&proc)
end

#match(req) ⇒ Object



49
50
51
# File 'lib/whales_dispatch/router.rb', line 49

def match(req)
  routes.select { |route| route.matches?(req) }.first
end

#resources(controller_noun, scope, **action_restrictions) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/whales_dispatch/router.rb', line 20

def resources(controller_noun, scope, **action_restrictions)
  @last_parent_route = "" if scope == :parent
  controller_actions = DefaultActions.new(controller_noun)
  controller_actions.parse_action_restrictions(action_restrictions)
  build_resources(controller_noun, controller_actions)

  if block_given?
    @last_parent_route = controller_noun.to_s
    yield
  end
end

#run(req, res) ⇒ Object



53
54
55
56
57
58
59
60
61
# File 'lib/whales_dispatch/router.rb', line 53

def run(req, res)
  route = match(req)
  if route
    route.run(req, res)
  else
    res.status = 404
    res.body = "Could not find matching route."
  end
end