Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to consider creating your own Ruby module in a Rails app?

Tags:

With a Ruby module, you can cluster together a bunch of methods that you might use in one place and then include them into a class so it's as if you had written them in that class.

What kinds of practical uses are there for Ruby modules in a rails app?

I would appreciate if someone could mention an example of where they've actually used a module of their own so I have a sense of what situations I should be thinking about creating them. Thanks.

like image 591
lorz Avatar asked May 31 '09 00:05

lorz


People also ask

Why we use module in Rails?

Modules are one of the shiniest resources of Ruby because they provide two great benefits: we can create namespaces to prevent name clashes and we can use them as mixins to share code across the application. Similar to classes, with modules we also group methods and constants and share code.

What is the difference between a class and a module Ruby?

What is the difference between a class and a module? Modules are collections of methods and constants. They cannot generate instances. Classes may generate instances (objects), and have per-instance state (instance variables).

What is the difference between module and concern?

Concern can appear somewhere as model, controller and at here you can write module for yourself. And with general module is write in lib folder. Both can be used by way include or extend into a class.

How do I add a module to 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. Now you should be able to do Customer. new. hello and get “hello” as a result.


2 Answers

1) Any time I'm about to duplicate (or substantially duplicate) a piece of code: "oh, i could just cut/paste into this other controller . . . "

2) Any time I write code that is very obviously going to be reused in the future.

3) Code of substantial size that has a specific purpose, where that purpose is fairly distinct from the main purpose of the controller/model. This is somewhat related to (2), but sometimes code won't get reused but a module helps for organization.

like image 170
klochner Avatar answered Oct 02 '22 23:10

klochner


You can place them in the /lib directory and they'll be loaded with your Rails project.

For example, you can view this repo of mine of an old project: lib directory of a Rails project

So for example, I have the following module:

google_charts.rb

Module GCharts
  class GoogleCharts
    def some_method

    end
  end
end

And anywhere in my Rails app, I can access the methods.

So if I were to access it from a controller, I would simply do:

require 'google_charts'

GCharts::GoogleCharts.some_method
like image 20
mwilliams Avatar answered Oct 02 '22 23:10

mwilliams