1
0
Fork 0
mirror of https://github.com/jnunemaker/httparty synced 2023-03-27 23:23:07 -04:00

Added callbacks

This commit is contained in:
John Nunemaker 2008-07-27 11:52:39 -04:00
parent df29a55264
commit be2ce8be39
4 changed files with 63 additions and 0 deletions

View file

@ -38,3 +38,4 @@ module Web
end
dir = File.expand_path(File.join(File.dirname(__FILE__), 'web'))
require dir + '/callbacks'

16
lib/web/callbacks.rb Normal file
View file

@ -0,0 +1,16 @@
module Web
module Callbacks
def callbacks
@callbacks ||= Hash.new { |h,k| h[k] = [] }
end
def add_callback(name, &block)
callbacks[name] << block
end
def run_callback(name, *args)
args = args.first if args.size == 1
callbacks[name].map { |block| block.call(args) }
end
end
end

9
lib/web/version.rb Normal file
View file

@ -0,0 +1,9 @@
module Web
module VERSION #:nodoc:
MAJOR = 0
MINOR = 0
TINY = 1
STRING = [MAJOR, MINOR, TINY].join('.')
end
end

View file

@ -0,0 +1,37 @@
require File.join(File.dirname(__FILE__), '..', 'spec_helper')
class Foo
extend Web::Callbacks
add_callback 'after_initialize' do
'running after_initialize'
end
add_callback 'after_request' do
'running after_request'
end
add_callback 'after_request' do
'another callback for after_request'
end
end
describe Web::Callbacks do
it 'should know the callbacks that have been added' do
Foo.callbacks.keys.should == %w[after_request after_initialize]
end
it 'should be able to add callbacks' do
Foo.add_callback('foobar') do
'do foobar'
end.first.kind_of?(Proc).should == true
end
it 'should be able to run a callback' do
Foo.run_callback('after_initialize').should == ['running after_initialize']
end
it 'should be able to run multiple callbacks' do
Foo.run_callback('after_request').should == ['running after_request', 'another callback for after_request']
end
end