Created
September 7, 2010 18:54
-
-
Save rstacruz/568846 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Main < Sinatra::Base | |
register Sinatra::Context | |
context "/post/:post_id" do | |
before do |post_id| | |
# This will be executed for all get/post/delete's in the current context. | |
@post = Post[post_id] | |
end | |
get do |post_id| | |
"You just visited /post/#{post_id} for the post {@post}" | |
end | |
get "/edit" do |post_id| | |
"You just visited /post/#{post_id}/edit for the post {@post}" | |
end | |
context "/comments" do | |
# Nesting contexts are okay | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Sinatra::Context | |
def self.registered(app) | |
app.extend ClassMethods | |
end | |
module ClassMethods | |
def context(prefix='', &b) | |
Context.new(prefix, self).instance_eval(&b) | |
end | |
end | |
class Context | |
def initialize(prefix, klass) | |
@prefix = prefix | |
@klass = klass | |
@before = nil | |
end | |
def before(&b) | |
@before = b | |
end | |
def method_missing(meth, *a, &b) | |
@klass.send(meth, *a, &b) | |
end | |
[ :get, :post, :delete, :context ].each do |action| | |
define_method action do |*a, &b| | |
before_action = @before | |
a[0] = "#{@prefix}#{a[0]}" | |
@klass.send(action, *a) do |*args| | |
before_action.call(*args) unless before_action.nil? | |
b.call(*args) | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment