mirror of
https://github.com/jnunemaker/httparty
synced 2023-03-27 23:23:07 -04:00
Added callbacks
This commit is contained in:
parent
df29a55264
commit
be2ce8be39
4 changed files with 63 additions and 0 deletions
|
@ -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
16
lib/web/callbacks.rb
Normal 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
9
lib/web/version.rb
Normal file
|
@ -0,0 +1,9 @@
|
|||
module Web
|
||||
module VERSION #:nodoc:
|
||||
MAJOR = 0
|
||||
MINOR = 0
|
||||
TINY = 1
|
||||
|
||||
STRING = [MAJOR, MINOR, TINY].join('.')
|
||||
end
|
||||
end
|
37
spec/spec/callbacks_spec.rb
Normal file
37
spec/spec/callbacks_spec.rb
Normal 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
|
Loading…
Reference in a new issue