Last active
August 29, 2015 14:21
-
-
Save maxim/971e39299691005c5161 to your computer and use it in GitHub Desktop.
Problem with Rails autoload and classes used for directory namespacing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# If you have the following setup, Rails autoload will depend on load order in a hard-to-trace way: | |
# app/models/foo.rb | |
class Foo | |
def initialize(arg) | |
@arg = arg | |
end | |
end | |
# app/models/foo/bar.rb | |
class Foo | |
class Bar | |
end | |
end | |
require 'foo/bar' | |
Foo.new('hello') # => wrong number of arguments (1 for 0) | |
# Rails already registered definition of Foo in file foo/bar.rb, which didn't have initialize. | |
# So it assumes that class Foo is already loaded, and has empty initialize. You get wrong number of args error. | |
# If you change app/models/foo/bar.rb to this: | |
class Foo::Bar | |
end | |
# Then this works: | |
require 'foo/bar' | |
Foo.new('hello') # => <Foo> | |
# because in this case the Foo inside foo/bar.rb was a mention, not a definition. | |
# Rails will go ahead and try to find the actual definition in foo.rb. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment