To make Rails autoload classes in library
I am using Rails 2.3.5, and in it, to autoload classes from lib folder, we just have to name the files according to their classnames
lib/auto_run.rb --> class AutoRun
lib/code_snippets/category_code --> class CodeSnippets::CategoryCode
It is similar to the Rails model naming except for the s. Here, I am confused about the latter one. Here, I havent defined a module or another class CodeSnippets anywhere. Then h开发者_Python百科ow can I use :: operator?
Also is there any other ways of folder structure so that Rails could autoload classes without writing extra code?
In CodeSnippets::CategoryCode
you don't need to declare CodeSnippets because it is not more than a namespace, it is not a Module or a Class
This classes just get autoloaded because by convention, all the files in lib/ get autoloaded, in the same way the /models and the controller/ folders get also autoloaded.
If you want to get more folders autoloaded you have to add them to the load_paths config variable in environment.rb like this:
config.load_paths += %W(#{RAILS_ROOT}/app/middleware)
config.load_paths += %W(#{RAILS_ROOT}/app/observers)
Just for sake of updating the answer: in Rails 4/5 you can just create a new folder in the app directory and it will be autoloaded and eager-loaded :-)
精彩评论