Skip to content

Commit

Permalink
added Class.callbacks_for_hook to cleanly access callbacks. version b…
Browse files Browse the repository at this point in the history
…ump.
  • Loading branch information
apotonick committed Oct 11, 2010
1 parent 420063a commit 4a13e4f
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 4 deletions.
4 changes: 2 additions & 2 deletions hooks.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@

Gem::Specification.new do |s|
s.name = %q{hooks}
s.version = "0.1.1"
s.version = "0.1.2"

s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Nick Sutterer"]
s.date = %q{2010-10-03}
s.date = %q{2010-10-11}
s.description = %q{Declaratively define hooks, add callbacks and run them with the options you like.}
s.email = %q{apotonick@gmail.com}
s.extra_rdoc_files = [
Expand Down
20 changes: 18 additions & 2 deletions lib/hooks.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
#
# cat.run_hook :after_dinner
module Hooks
VERSION = "0.1.1"
VERSION = "0.1.2"

def self.included(base)
base.extend InheritableAttribute
Expand Down Expand Up @@ -46,13 +46,29 @@ def run_hook(name, *args)
end

def run_hook_for(name, scope, *args)
send("_#{name}_callbacks").each do |callback|
callbacks_for_hook(name).each do |callback|
scope.send(callback, *args) and next if callback.kind_of? Symbol
callback.call(*args)
end
end

# Returns the callbacks for +name+. Handy if you want to run the callbacks yourself, say when
# they should be executed in another context.
#
# Example:
#
# def initialize
# self.class.callbacks_for_hook(:after_eight).each do |callback|
# instance_exec(self, &callback)
# end
#
# would run callbacks in the object _instance_ context, passing +self+ as block parameter.
def callbacks_for_hook(name)
send("_#{name}_callbacks")
end

private

def define_hook_writer(hook, accessor_name)
instance_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
def #{hook}(method=nil, &block)
Expand Down
6 changes: 6 additions & 0 deletions test/hooks_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ def executed
@klass._after_eight_callbacks << :dine
assert_equal [:dine], @klass._after_eight_callbacks
end

should "respond to Class.callbacks_for_hook" do
assert_equal [], @klass.callbacks_for_hook(:after_eight)
@klass.after_eight :dine
assert_equal [:dine], @klass.callbacks_for_hook(:after_eight)
end

context "creates a public writer for the hook that" do
should "accepts method names" do
Expand Down

0 comments on commit 4a13e4f

Please sign in to comment.