shiningthrough

A simple example of using Modules with Ruby On Rails

18 July 2011

A module provides a means of grouping together classes, methods and constants.

This is advantageous for two reasons:

Lets see this in action with a simple example:

We create a module called TextStatistics, in a file called text_statistics.rb, which we place in the lib directory.

module TextStatistics
  def word_count
    self.body.scan(/\w+/).size
  end
  
  def letter_count
    self.body.scan(/./).size
  end
end

We can then "mixin" this module into both our classes.

class Article < ActiveRecord::Base
  include TextStatistics
end
class Comment < ActiveRecord::Base
  include TextStatistics
end

allowing us to write code like this

<%= @article.word_count %>

and this

<%= @comment.letter_count %>

Comments