Class: Rory::Dispatcher

Inherits:
Object
  • Object
show all
Defined in:
lib/rory/dispatcher.rb

Overview

The dispatcher takes care of sending an incoming request to the appropriate controller, after examining the routes.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(rack_request, app = nil) ⇒ Dispatcher

Returns a new instance of Dispatcher.



6
7
8
9
10
# File 'lib/rory/dispatcher.rb', line 6

def initialize(rack_request, app = nil)
  @request = rack_request
  @routing = {}
  @app = app
end

Instance Attribute Details

#requestObject (readonly)

Returns the value of attribute request.



5
6
7
# File 'lib/rory/dispatcher.rb', line 5

def request
  @request
end

Class Method Details

.rack_app(app) ⇒ Object



12
13
14
15
16
# File 'lib/rory/dispatcher.rb', line 12

def self.rack_app(app)
  Proc.new { |env|
    new(Rory::Request.new(env), app).dispatch
  }
end

Instance Method Details

#dispatchObject



50
51
52
53
54
55
56
# File 'lib/rory/dispatcher.rb', line 50

def dispatch
  if controller
    controller.present
  else
    render_not_found
  end
end

#extensionObject



26
27
28
# File 'lib/rory/dispatcher.rb', line 26

def extension
  File.extname(full_path)[1..-1]
end

#full_pathObject



34
35
36
# File 'lib/rory/dispatcher.rb', line 34

def full_path
  @request.path_info[1..-1] || ''
end

#json_requested?Boolean

Returns:

  • (Boolean)


30
31
32
# File 'lib/rory/dispatcher.rb', line 30

def json_requested?
  extension == 'json'
end

#methodObject



42
43
44
# File 'lib/rory/dispatcher.rb', line 42

def method
  override_method || request.request_method.downcase
end

#override_methodObject



18
19
20
21
22
23
24
# File 'lib/rory/dispatcher.rb', line 18

def override_method
  requested_override = request.params['_method']
  return nil unless requested_override
  if ['put', 'patch', 'delete'].include?(requested_override.downcase)
    requested_override.downcase
  end
end

#path_without_extensionObject



38
39
40
# File 'lib/rory/dispatcher.rb', line 38

def path_without_extension
  full_path.gsub(/(.*)\.#{extension}$/, '\1')
end

#redirect(path = '/') ⇒ Object



58
59
60
61
62
63
# File 'lib/rory/dispatcher.rb', line 58

def redirect(path = '/')
  unless path =~ /\:\/\//
    path = "#{@request.scheme}://#{@request.host_with_port}#{path}"
  end
  return [ 302, {'Content-type' => 'text/html', 'Location'=> path }, ['Redirecting...'] ]
end

#render_not_foundObject



65
66
67
# File 'lib/rory/dispatcher.rb', line 65

def render_not_found
  return [ 404, {'Content-type' => 'text/html' }, ['Four, oh, four.'] ]
end

#routeObject



46
47
48
# File 'lib/rory/dispatcher.rb', line 46

def route
  @routing[:route] ||= get_route
end