diff options
Diffstat (limited to 'railties')
-rw-r--r-- | railties/lib/rails/initializable.rb | 42 | ||||
-rw-r--r-- | railties/test/initializable_test.rb | 8 |
2 files changed, 44 insertions, 6 deletions
diff --git a/railties/lib/rails/initializable.rb b/railties/lib/rails/initializable.rb index 93349454dd..d78eab9a75 100644 --- a/railties/lib/rails/initializable.rb +++ b/railties/lib/rails/initializable.rb @@ -4,8 +4,35 @@ module Rails base.extend ClassMethods end - Initializer = Struct.new(:name, :before, :after, :global, :block) do + class Initializer + attr_reader :name, :before, :after, :global, :block + + def initialize(name, context, options, &block) + @name, @context, @options, @block = name, context, options, block + end + + def before + @options[:before] + end + + def after + @options[:after] + end + + def global + @options[:global] + end + alias global? global + + def run(*args) + @context.instance_exec(*args, &block) + end + + def bind(context) + return self if @context + Initializer.new(@name, context, @options, &block) + end end class Collection < Array @@ -35,12 +62,19 @@ module Rails def run_initializers(*args) return if @ran - self.class.initializers_for(:instance).each do |initializer| - instance_exec(*args, &initializer.block) + initializers.each do |initializer| + initializer.run(*args) end @ran = true end + def initializers + @initializers ||= begin + initializers = self.class.initializers_for(:instance) + Collection.new(initializers.map { |i| i.bind(self) }) + end + end + module ClassMethods def initializers @initializers ||= [] @@ -59,7 +93,7 @@ module Rails def initializer(name, opts = {}, &blk) @initializers ||= [] - @initializers << Initializer.new(name, opts[:before], opts[:after], opts[:global], blk) + @initializers << Initializer.new(name, nil, opts, &blk) end def run_initializers(*args) diff --git a/railties/test/initializable_test.rb b/railties/test/initializable_test.rb index 463fdc03c0..2920883132 100644 --- a/railties/test/initializable_test.rb +++ b/railties/test/initializable_test.rb @@ -94,7 +94,11 @@ module InitializableTests include Rails::Initializable initializer :startup, :before => :last do - $arr << 2 + $arr << two + end + + def two + 2 end end @@ -109,7 +113,7 @@ module InitializableTests end def self.initializers - super + MoreInitializers.initializers + super + MoreInitializers.new.initializers end end |