Permalink
Browse files

added Class.callbacks_for_hook to cleanly access callbacks. version b…

…ump.
  • Loading branch information...
1 parent 420063a commit 4a13e4f2b7ff1533b9793dfa5140e08ffb74851b @apotonick committed Oct 11, 2010
Showing with 26 additions and 4 deletions.
  1. +2 −2 hooks.gemspec
  2. +18 −2 lib/hooks.rb
  3. +6 −0 test/hooks_test.rb
View
4 hooks.gemspec
@@ -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 = [
View
20 lib/hooks.rb
@@ -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
@@ -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)
View
6 test/hooks_test.rb
@@ -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

0 comments on commit 4a13e4f

Please sign in to comment.