Skip to content

Instantly share code, notes, and snippets.

@timuruski
Created August 9, 2011 04:30
Show Gist options
  • Select an option

  • Save timuruski/1133417 to your computer and use it in GitHub Desktop.

Select an option

Save timuruski/1133417 to your computer and use it in GitHub Desktop.
An example implementation of automatic controllers in Sinatra.
require 'sinatra'
require 'rack/test'
class FooController
def index
"Hello, foo!"
end
end
class BarController
def self.default_path
"/bar"
end
def index
"Hello, bar!"
end
end
module Sinatra
module Controllers
def register_controller(controller, params = {})
@controller_map_list ||= ControllerMapList.new
@controller_map_list << ControllerMapping.new(controller, params)
end
def controller_map_list
@controller_map_list
end
def self.registered(app)
app.helpers do
def find_controller
self.class.controller_map_list.find_match(request.path)
end
end
app.before do
@controller = find_controller
end
end
end
class ControllerMapList
def initialize
@list = []
end
def <<(mapping)
@list << mapping
end
def find_match(path)
match = @list.find { |mapping| mapping.match(path) }
match.controller.new unless match.nil?
end
end
class ControllerMapping
attr_reader :controller
def initialize(controller, params)
@controller = controller
@path = params[:path]
@path ||= controller.default_path if controller.respond_to?(:default_path)
end
def match(request_path)
request_path.start_with?(@path)
end
end
end
class ExampleApp < Sinatra::Base
register Sinatra::Controllers
register_controller FooController, :path => '/foo'
register_controller BarController
get "/foo/" do
@controller.index
end
get "/bar/" do
@controller.index
end
end
describe "Sinatra::Controllers" do
include Rack::Test::Methods
def app
ExampleApp.new
end
it "works" do
get "/foo/"
last_response.should be_ok
last_response.body.should == "Hello, foo!"
end
it "works" do
get "/bar/"
last_response.should be_ok
last_response.body.should == "Hello, bar!"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment