Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autoloading from namespace inside a custom folder in app

We're currently developing a custom cms engine for ROR 3.2. In this process several class types originated that we want to be first class citizens in our rails application, meaning they should reside under the app folder of the application and it's plugins.

Currently we're having the following types:

  • DataSource
  • DataType
  • View

I created multible directories under the app folder to hold these:

  • app/data_source
  • app/data_type
  • app/view

More types will follow and I'm a little worried with polluting the app folder with so many directories. Thus i want to move them into a subdirectory/module that holds all Types defined by the cms.

All classes should be inside a MyCms namespace and the directory layout should look like this:

  • app/my_cms/data_source
  • app/my_cms/data_type
  • app/my_cms/view

But now I'm having trouble with autoloading because rails default autoloading would excpect the paths to be like this:

  • app/data_source/my_cms
  • app/data_type/my_cms
  • app/view/my_cms

But this way I would not have grouped all object types in one directory.

What I want is somewhat similar to view grouping of isolated engines. In Devise for example, all views are grouped in the views/devise subdirectory.

Any idea how this could be achieved without to much custom implementation?

like image 844
room13 Avatar asked Jan 24 '13 08:01

room13


1 Answers

You would have to add app/my_cms to your autoload path within config/application.rb:

config.autoload_paths << "#{config.root}/app/my_cms"

provided that your classes are defined without a namespace like this:

class DataSource
  ...
end

If you namespace them like this in app/my_cms/data_source.rb:

class MyCms::DataSource
  ...
end

you might add the app folder to the load path:

config.autoload_paths << "#{config.root}/app"

Alternatively, you can do it manually but you lose the reloading for those classes in Rails development:

in app/my_cms.rb (and with autoloading for app in place):

module MyCms
  autoload :AnotherDataSource, 'my_cms/data_source/one_data_source'
  autoload :AnotherDataSource, 'my_cms/data_source/another_data_source'

  ...
end
like image 104
moritz Avatar answered Nov 16 '22 15:11

moritz