Automatically creating a containing class module

In Rails, you can create a model under app/foo/bar.rb , where bar.rb contains:

 class Foo::Bar def some_method puts "I work fine" end end 

If you try to do this in a pure ruby ​​application, you will get NameError: uninitialized constant Foo if you have not initialized the Foo module.

What does Rails do that allow you to create classes without first initializing their containing module? Is it possible to import this behavior through something like activesupport, or have we left it on our own?

+4
source share
2 answers

Rails modifies the Class class to include the const_missing method, which is called when an undefined class is used. Then it loads things to try to load the requested class.

An implementation of this in ActiveSupport is in lib/active_support/dependencies.rb .

+3
source

the model class actually created extends to <ActiveRecord :: Base

-1
source

All Articles