Sha256: aacbbbe104eb97969deb3058e180bcb9129bb1bbfb51d6ff3a4656daea4773a5

Contents?: true

Size: 1.5 KB

Versions: 3

Compression:

Stored size: 1.5 KB

Contents

%w{
active_record
rack

murlsh
}.each { |m| require m }

module Murlsh

  # Dispatch requests.
  class Dispatch

    # Set up database connection and dispatch table.
    def initialize(config)
      @config = config

      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)
      flickr_server = Murlsh::FlickrServer.new(@config)
      twitter_server = Murlsh::TwitterServer.new

      root_path = URI(@config.fetch('root_url')).path

      @dispatch = [
        [%r{^GET #{root_path}(url)?$}, url_server.method(:get)],
        [%r{^POST #{root_path}(url)?$}, url_server.method(:post)],
        [%r{^GET /flickr$}, flickr_server.method(:get)],
        [%r{^GET /twitter/.+$}, twitter_server.method(:get)],
      ]
    end

    # Figure out which method will handle request.
    def dispatch(req)
      method_match = @dispatch.find do |rule|
        rule[0].match("#{req.request_method} #{req.path}")
      end

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

    # Rack call.
    def call(env)
      req = Rack::Request.new(env)
      dispatch(req).call(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

3 entries across 3 versions & 1 rubygems

Version Path
murlsh-0.9.0 lib/murlsh/dispatch.rb
murlsh-0.8.1 lib/murlsh/dispatch.rb
murlsh-0.8.0 lib/murlsh/dispatch.rb