Skip to content

Commit

Permalink
Ensure load hooks can be called more than once with different contexts.
Browse files Browse the repository at this point in the history
  • Loading branch information
josevalim committed Mar 6, 2012
1 parent bc5ac77 commit d1a4faf
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
12 changes: 6 additions & 6 deletions activesupport/lib/active_support/lazy_load_hooks.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@ module ActiveSupport
#
# ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base)
#
@load_hooks = Hash.new {|h,k| h[k] = [] }
@loaded = {}
@load_hooks = Hash.new { |h,k| h[k] = [] }
@loaded = Hash.new { |h,k| h[k] = [] }

def self.on_load(name, options = {}, &block)
if base = @loaded[name]
@loaded[name].each do |base|
execute_hook(base, options, block)
else
@load_hooks[name] << [block, options]
end

@load_hooks[name] << [block, options]
end

def self.execute_hook(base, options, block)
Expand All @@ -38,7 +38,7 @@ def self.execute_hook(base, options, block)
end

def self.run_load_hooks(name, base = Object)
@loaded[name] = base
@loaded[name] << base
@load_hooks[name].each do |hook, options|
execute_hook(base, options, hook)
end
Expand Down
29 changes: 29 additions & 0 deletions activesupport/test/lazy_load_hooks_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,16 @@ def test_basic_hook
assert_equal 1, i
end

def test_basic_hook_with_two_registrations
i = 0
ActiveSupport.on_load(:basic_hook_with_two) { i += incr }
assert_equal 0, i
ActiveSupport.run_load_hooks(:basic_hook_with_two, FakeContext.new(2))
assert_equal 2, i
ActiveSupport.run_load_hooks(:basic_hook_with_two, FakeContext.new(5))
assert_equal 7, i
end

def test_hook_registered_after_run
i = 0
ActiveSupport.run_load_hooks(:registered_after)
Expand All @@ -16,6 +26,25 @@ def test_hook_registered_after_run
assert_equal 1, i
end

def test_hook_registered_after_run_with_two_registrations
i = 0
ActiveSupport.run_load_hooks(:registered_after_with_two, FakeContext.new(2))
ActiveSupport.run_load_hooks(:registered_after_with_two, FakeContext.new(5))
assert_equal 0, i
ActiveSupport.on_load(:registered_after_with_two) { i += incr }
assert_equal 7, i
end

def test_hook_registered_interleaved_run_with_two_registrations
i = 0
ActiveSupport.run_load_hooks(:registered_interleaved_with_two, FakeContext.new(2))
assert_equal 0, i
ActiveSupport.on_load(:registered_interleaved_with_two) { i += incr }
assert_equal 2, i
ActiveSupport.run_load_hooks(:registered_interleaved_with_two, FakeContext.new(5))
assert_equal 7, i
end

def test_hook_receives_a_context
i = 0
ActiveSupport.on_load(:contextual) { i += incr }
Expand Down

0 comments on commit d1a4faf

Please sign in to comment.