Reputation: 3175
In Rails you can create a model under app/foo/bar.rb
, with bar.rb containing:
class Foo::Bar
def some_method
puts "I work fine"
end
end
If you try to do this in a pure ruby app you'd get a NameError: uninitialized constant Foo
unless you've already initialized a module Foo
.
What is Rails doing that allows it to create classes without first initializing their containing module? Is it possible to import this behavior through something like activesupport, or are we left to implement on our own?
Upvotes: 4
Views: 318
Reputation: 5948
Rails modifies the Class
class to include a const_missing
method which gets called when an undefined class is used. It then loads things to try and load the requested class.
The implementation of this in ActiveSupport is in lib/active_support/dependencies.rb
.
Upvotes: 3