Sha256: 1bda7664a6d194eb825b47b9530644db41d7b37915e9e10dd14618073f7c0f44

Contents?: true

Size: 1.25 KB

Versions: 7

Compression:

Stored size: 1.25 KB

Contents

%w{
murlsh

rubygems
active_record
rack
sqlite3

yaml
}.each { |m| require m }

module Murlsh

  # Dispatch requests.
  class Dispatch

    # Set up config hash and database connection.
    def initialize
      @config = YAML.load_file('config.yaml')
      @url_root = URI(@config.fetch('root_url')).path

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

      @db = ActiveRecord::Base.connection.instance_variable_get(:@connection)

      @url_server = Murlsh::UrlServer.new(@config, @db)
    end

    # Rack call.
    def call(env)
      dispatch = {
        ['GET', @url_root] => [@url_server, :get],
        ['POST', @url_root] => [@url_server, :post],
        ['GET', "#{@url_root}url"] => [@url_server, :get],
        ['POST', "#{@url_root}url"] => [@url_server, :post],
      }
      dispatch.default = [self, :not_found]

      req = Rack::Request.new(env)

      obj, meth = dispatch[[req.request_method, req.path]]

      obj.send(meth, req).finish
    end

    # Called if the request is not found.
    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

  end

end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
murlsh-0.6.1 lib/murlsh/dispatch.rb
murlsh-0.6.0 lib/murlsh/dispatch.rb
murlsh-0.5.2 lib/murlsh/dispatch.rb
murlsh-0.5.1 lib/murlsh/dispatch.rb
murlsh-0.5.0 lib/murlsh/dispatch.rb
murlsh-0.4.0 lib/murlsh/dispatch.rb
murlsh-0.3.0 lib/murlsh/dispatch.rb