Permalink
Browse files

Add the ability to merge initializers from various objects in order.

  • Loading branch information...
1 parent 897164d commit 43694269934540de2a73130d7ff47bd1a25ed3e4 Yehuda Katz + Carl Lerche committed Nov 5, 2009
Showing with 44 additions and 6 deletions.
  1. +38 −4 railties/lib/rails/initializable.rb
  2. +6 −2 railties/test/initializable_test.rb
@@ -4,8 +4,35 @@ def self.included(base)
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 @@ def index_for(name)
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 @@ def initializers_for(scope = :global)
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)
@@ -94,7 +94,11 @@ class MoreInitializers
include Rails::Initializable
initializer :startup, :before => :last do
- $arr << 2
+ $arr << two
+ end
+
+ def two
+ 2
end
end
@@ -109,7 +113,7 @@ class MoreInitializers
end
def self.initializers
- super + MoreInitializers.initializers
+ super + MoreInitializers.new.initializers
end
end

1 comment on commit 4369426

Please sign in to comment.