Class: Murlsh::Dispatch

Inherits:
Object
  • Object
show all
Defined in:
lib/murlsh/dispatch.rb

Overview

Dispatch requests.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Dispatch

Set up database connection and dispatch table.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/murlsh/dispatch.rb', line 14

def initialize(config)
  @config = config

  url_server = Murlsh::UrlServer.new(config)
  config_server = Murlsh::ConfigServer.new(config)
  root_path = URI(config.fetch('root_url')).path

  @routes = [
    [%r{^HEAD #{root_path}(url)?$}, url_server.method(:head)],
    [%r{^GET #{root_path}(url)?$}, url_server.method(:get)],
    [%r{^POST #{root_path}(url)?$}, url_server.method(:post)],
    [%r{^HEAD #{root_path}config$}, config_server.method(:head)],
    [%r{^GET #{root_path}config$}, config_server.method(:get)],
  ]

  db_init
end

Instance Attribute Details

#routesObject

Returns the value of attribute routes.



65
66
67
# File 'lib/murlsh/dispatch.rb', line 65

def routes
  @routes
end

Instance Method Details

#call(env) ⇒ Object

Rack call.



51
52
53
54
# File 'lib/murlsh/dispatch.rb', line 51

def call(env)
  req = Rack::Request.new(env)
  dispatch(req).call(req).finish
end

#db_initObject



32
33
34
35
36
37
38
39
# File 'lib/murlsh/dispatch.rb', line 32

def db_init
  ActiveRecord::Base.establish_connection(
    :adapter => 'sqlite3', :database => @config.fetch('db_file'))

  ActiveRecord::Base.default_timezone = :utc
  ActiveRecord::Base.include_root_in_json = false
  # ActiveRecord::Base.logger = Logger.new(STDERR)
end

#dispatch(req) ⇒ Object

Figure out which method will handle request.



42
43
44
45
46
47
48
# File 'lib/murlsh/dispatch.rb', line 42

def dispatch(req)
  method_match = routes.find do |rule|
    rule[0].match("#{req.request_method} #{req.path}")
  end

  method_match ? method_match[1] : self.method(:not_found)
end

#not_found(req) ⇒ Object

Called if the request is not found.



57
58
59
60
61
62
63
# File 'lib/murlsh/dispatch.rb', line 57

def not_found(req)
  Rack::Response.new "<p>#{req.url} not found</p>

<p><a href=\"#{@config['root_url']}\">root<a></p>
",
    404, { 'Content-Type' => 'text/html' }
end