Skip to content

Commit

Permalink
Add registered callback for extension modules [#148]
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
rtomayko committed Feb 24, 2009
1 parent 9460520 commit eba6de6
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
11 changes: 7 additions & 4 deletions lib/sinatra/base.rb
Expand Up @@ -716,13 +716,16 @@ def compile(path)

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
Expand Down
21 changes: 21 additions & 0 deletions test/extensions_test.rb
Expand Up @@ -60,4 +60,25 @@ def im_in_ur_anonymous_module; end
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

0 comments on commit eba6de6

Please sign in to comment.