From c094757b080e945939a0112572cb19761ec894b6 Mon Sep 17 00:00:00 2001 From: Nicolas Sanguinetti Date: Mon, 26 Jan 2009 17:08:16 -0200 Subject: [PATCH] Add #helpers into Sinatra::Base [#134 state:resolved] Signed-off-by: Ryan Tomayko --- lib/sinatra/base.rb | 7 ++++++- lib/sinatra/main.rb | 7 ------- test/helpers_test.rb | 42 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+), 8 deletions(-) diff --git a/lib/sinatra/base.rb b/lib/sinatra/base.rb index 25fc5460..abb1c664 100644 --- a/lib/sinatra/base.rb +++ b/lib/sinatra/base.rb @@ -658,6 +658,11 @@ module Sinatra end public + def helpers(*modules, &block) + include *modules unless modules.empty? + class_eval(&block) if block + end + def development? ; environment == :development ; end def test? ; environment == :test ; end def production? ; environment == :production ; end @@ -900,7 +905,7 @@ module Sinatra delegate :get, :put, :post, :delete, :head, :template, :layout, :before, :error, :not_found, :configures, :configure, :set, :set_option, :set_options, :enable, :disable, :use, :development?, :test?, - :production?, :use_in_file_templates! + :production?, :use_in_file_templates!, :helpers end def self.new(base=Base, options={}, &block) diff --git a/lib/sinatra/main.rb b/lib/sinatra/main.rb index cf2ca9f5..1dc0b10f 100644 --- a/lib/sinatra/main.rb +++ b/lib/sinatra/main.rb @@ -32,13 +32,6 @@ end include Sinatra::Delegator -def helpers(*modules, &block) - Sinatra::Application.class_eval do - modules.each {|m| include m } - end - Sinatra::Application.class_eval(&block) -end - def mime(ext, type) ext = ".#{ext}" unless ext.to_s[0] == ?. Rack::Mime::MIME_TYPES[ext.to_s] = type diff --git a/test/helpers_test.rb b/test/helpers_test.rb index b272ec89..c397dc86 100644 --- a/test/helpers_test.rb +++ b/test/helpers_test.rb @@ -379,3 +379,45 @@ describe 'Helpers#etag' do assert_equal 'W/"FOO"', response['ETag'] end end + +describe 'Adding new helpers' do + module HelperOne; def one; '1'; end; end + module HelperTwo; def two; '2'; end; end + + it 'should allow passing a list of modules' do + mock_app { + helpers HelperOne, HelperTwo + + get '/one' do + one + end + + get '/two' do + two + end + } + + get '/one' + assert_equal '1', body + + get '/two' + assert_equal '2', body + end + + it 'should take a block and mix it into the app' do + mock_app { + helpers do + def foo + 'foo' + end + end + + get '/' do + foo + end + } + + get '/' + assert_equal 'foo', body + end +end