Skip to content

Instantly share code, notes, and snippets.

@maxim
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxim/971e39299691005c5161 to your computer and use it in GitHub Desktop.
Save maxim/971e39299691005c5161 to your computer and use it in GitHub Desktop.
Problem with Rails autoload and classes used for directory namespacing
# 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