Add registered callback for extension modules [#148]

The "registered" message is sent to extension modules immediately
after the module is mixed into a Sinatra::Base class. This can be
used to initialize the class with options, add templates, define
error handlers, etc.
This commit is contained in:
Ryan Tomayko 2009-02-22 01:51:39 -08:00
parent 9460520723
commit eba6de6970
2 changed files with 28 additions and 4 deletions

View File

@ -716,13 +716,16 @@ module Sinatra
public
def helpers(*extensions, &block)
class_eval(&block) if block_given?
include *extensions
class_eval(&block) if block_given?
include *extensions if extensions.any?
end
def register(*extensions, &block)
extensions << Module.new(&block) if block
extend *extensions
extensions << Module.new(&block) if block_given?
extensions.each do |extension|
extend extension
extension.registered(self) if extension.respond_to?(:registered)
end
end
def development? ; environment == :development ; end

View File

@ -60,4 +60,25 @@ describe 'Registering extensions' do
assert !Sinatra::Base.respond_to?(:baz)
assert Sinatra::Default.respond_to?(:baz)
end
module BizzleExtension
def bizzle
bizzle_option
end
def self.registered(base)
fail "base should be BizzleApp" unless base == BizzleApp
fail "base should have already extended BizzleExtension" unless base.respond_to?(:bizzle)
base.set :bizzle_option, 'bizzle!'
end
end
class BizzleApp < Sinatra::Base
end
it 'sends .registered to the extension module after extending the class' do
BizzleApp.register BizzleExtension
assert_equal 'bizzle!', BizzleApp.bizzle_option
assert_equal 'bizzle!', BizzleApp.bizzle
end
end