Skip to content

Commit 5a0d73f

Browse files
committed
Add lib to load paths when application is inherited to be able to load lib code during configuration.
1 parent cae2519 commit 5a0d73f

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

railties/lib/rails/application.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ def inherited(base)
6767
raise "You cannot have more than one Rails::Application" if Rails.application
6868
super
6969
Rails.application = base.instance
70+
Rails.application.add_lib_to_load_paths!
7071
ActiveSupport.run_load_hooks(:before_configuration, base.instance)
7172
end
7273

@@ -83,11 +84,21 @@ def method_missing(*args, &block)
8384

8485
delegate :middleware, :to => :config
8586

87+
def add_lib_to_load_paths!
88+
path = config.root.join('lib').to_s
89+
$LOAD_PATH.unshift(path) if File.exists?(path)
90+
end
91+
8692
def require_environment!
8793
environment = paths.config.environment.to_a.first
8894
require environment if environment
8995
end
9096

97+
def eager_load!
98+
railties.all(&:eager_load!)
99+
super
100+
end
101+
91102
def routes
92103
@routes ||= ActionDispatch::Routing::RouteSet.new
93104
end

railties/lib/rails/application/finisher.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ module Finisher
3838
initializer :eager_load! do
3939
if config.cache_classes && !$rails_rake_task
4040
ActiveSupport.run_load_hooks(:before_eager_load, self)
41-
railties.all(&:eager_load!)
41+
eager_load!
4242
end
4343
end
4444

railties/test/application/initializers/load_path_test.rb

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,23 @@ def setup
1919
assert $:.include?("#{app_path}/app/models")
2020
end
2121

22+
test "initializing an application adds lib path on inheritance hook" do
23+
app_file "lib/foo.rb", <<-RUBY
24+
module Foo; end
25+
RUBY
26+
27+
add_to_config <<-RUBY
28+
require "foo"
29+
raise "Expected Foo to be defined" unless defined?(Foo)
30+
RUBY
31+
32+
assert_nothing_raised do
33+
require "#{app_path}/config/environment"
34+
end
35+
36+
assert $:.include?("#{app_path}/lib")
37+
end
38+
2239
test "initializing an application eager load any path under app" do
2340
app_file "app/anything/foo.rb", <<-RUBY
2441
module Foo; end

0 commit comments

Comments
 (0)