Using Rails’ descendants in development

Rails provides a nice method descendants that returns all subclasses for a specified class. However, config.cache_classes = false is a default setting in development.rb (for the ability to reload classes on the fly) and as this tells Rails not to load classes until they are referenced, then calling descendants will generally return an empty array not the expected subclasses.

To be able to use descendants in development, you can add the following code to development.rb:

config.eager_load_paths += Dir['path/to/files/*.rb']
ActionDispatch::Reloader.to_prepare do
Dir['path/to/files/*.rb'].each {|file| require_dependency file}
end

The first line tells Rails to load these particular files when Rails first starts up. The rest of the code tells Rails to require these particular files (including any new files/classes) on each request.

Note: if your path/to/files isn’t one of the standard directories that Rails watches (to trigger the reloader), you will need to add it to config.watchable_dirs:

config.watchable_dirs['path/to/files/'] = [:rb]

Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *