Skip to content

Instantly share code, notes, and snippets.

@rstacruz
Created September 7, 2010 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rstacruz/568846 to your computer and use it in GitHub Desktop.
Save rstacruz/568846 to your computer and use it in GitHub Desktop.
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
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