I am using Ruby on Rails 3 and I would like to move some custom and shared code in a module.
- What syntax should I use to write the module code?
- In which folder of my application I have to place the module file?
- How I have to include that module in one or more controller classes?
- What other action, if any, do I have to use the custom module anywhere in my application?
- How can I call methods in the module from my application?
To 1. A module is created/opened
by simply saying:
To 2. The
libfolder. If you want to organize your modules in thelibfolder, you can put them into modules themselves. For example, if you wanted a subfoldersuper_modulesyour modules would be defined as follows:To 3./5. When including the module in a class you can simply call the modules methods as if they were defined within the class:
To 4.
Frst, make sure that your module is really needed in every class of your application. If it isn’t it makes sense to only include it where it is need so as not to bloat the classes that don’t need it anyways. If you really want the module everywhere, include look at the class hierarchy of your classes in the app. Do you want the module in all models? You could open ActiveRecord::Base and add add your module there.