Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create and use a module using Ruby on Rails 3?

I am using Ruby on Rails 3 and I would like to move some custom and shared code in a module.

  1. What syntax should I use to write the module code?
  2. In which folder of my application I have to place the module file?
  3. How I have to include that module in one or more controller classes?
  4. What other action, if any, do I have to use the custom module anywhere in my application?
  5. How can I call methods in the module from my application?

Thanks in advance.

like image 812
user502052 Avatar asked Feb 05 '11 12:02

user502052


People also ask

How do you create a module in Ruby?

Creating Modules in Ruby To define a module, use the module keyword, give it a name and then finish with an end . The module name follows the same rules as class names. The name is a constant and should start with a capital letter. If the module is two words it should be camel case (e.g MyModule).

How do I add a module in Rails?

You can include a module in a class in your Rails project by using the include keyword followed by the name of your module.

What is module in Ruby on Rails?

Modules are a way of grouping together methods, classes, and constants. Modules give you two major benefits. Modules provide a namespace and prevent name clashes.


1 Answers

To 1. A module is created/opened by simply saying:

module MyModule   def first_module_method   end end 

To 2. The lib folder. If you want to organize your modules in the lib folder, you can put them into modules themselves. For example, if you wanted a subfolder super_modules your modules would be defined as follows:

module SuperModules   module MyModule     def first_module_method     end   end end 

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:

class MyClass   include MyModule   def some_method     first_module_method #calls module method   end end 

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.

like image 54
Stephan Avatar answered Oct 02 '22 20:10

Stephan