Class: Routing

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

Instance Method Summary collapse

Constructor Details

#initialize(request) ⇒ Routing

Set request object as an attribute. Declare a routes attribute. Call the draw method to populate it with a hash of routes.



4
5
6
7
8
# File 'lib/jails/routing.rb', line 4

def initialize(request)
  @request = request
  @routes = {} 
  draw(Application.routes)
end

Instance Method Details

#dispatchObject

Match request path to @routes hash. If match, create controller object and call the action.



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/jails/routing.rb', line 21

def dispatch
  path = @request.path
  id = nil
  segments = path.split("/").reject { |segment| segment.empty? }
  if segments[1] =~ /^\d+$/
    id = segments[1]
    segments[1] = ":id"
    path = "/#{segments.join('/')}"
  end
  if @routes.key?(path)
    target = @routes[path]
    resource_name, action_name = target.split('#')
    @request.params.merge!(resource: resource_name, action: action_name, id: id)
    klass = Object.const_get("#{resource_name.capitalize}Controller")
    puts("Processing by #{klass}##{action_name}")
    klass.new(@request).send(action_name)
  else
    Rack::Response.new(["Nothing found"], 404, {"Content-Type" => "text/html"})
  end
rescue Exception => error
  Rack::Response.new(["Internal error"], 500, {"Content-Type" => "text/html"})
end

#draw(block) ⇒ Object

Build the @routes hash by evaluating the block passed in as a proc object from the Application.routes method.



11
12
13
# File 'lib/jails/routing.rb', line 11

def draw(block)   
  instance_eval(&block)
end

#match(path, target) ⇒ Object

Add route to @routes hash with the url’s path as the key and target as the value.



16
17
18
# File 'lib/jails/routing.rb', line 16

def match(path, target)
  @routes["#{path}"] = target
end