views:

798

answers:

3

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.

+5  A: 

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
mwilliams
Thanks. The implementation details are good to know about. But I was thinking more along the lines of what types of functionality in a Rails app you would use a module for encapsulating.
lorz
Anything that doesn't belong in your controller or model :). In other projects, we've had a utilities.rb that didn't really have a place within any controller/helper/model but were necessary. So we tucked them away in the lib directory. Also, other libraries that we write that don't need to be their own plugin.
mwilliams
How do you determine when something falls short of being a plugin but doesn't belong in the controller or model?
lorz
Maybe it's a temporary thing or something just so trivial that we don't want to go through the trouble of making it a full blown plugin. At that point, it's really just a decision that won't really matter one way or another. It's a matter of preference of you, as the developer and what's going to make you happy.
mwilliams
+5  A: 

We use modules for functionality that isn't tied to ActiveRecord models and hasn't been abstracted into a plugin or gem.

A recent example from our production code base is a library for integrating with Campaign Monitor for email list management. The core of the system uses our user model, but the actual interaction with the extenrl service is abstracted through a module that lives in /lib.

Toby Hede
+2  A: 

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.

klochner