Blog Ruby Maths

Modules and Mixins

Within Ruby object model, we can include modules. By including a module into a class, we can add instance methods, extend a class with a module, create a namespace with a module, distinguish between prepending modules into classes and including and extending them and use modules to address multiple inheritance in Ruby.

Including Modules
 
Let's say we have User and Building class. The Postal address is needed for these two classes.

User class

class User
  attr_accessor :address_line1, :address_line2, :city, :state,
    :postal_code, :country
  def mailing_label
    label = []
    label << address_line1
    label << address_line2
    label << "#{city}, #{state} #{postal_code}"
    label << country
    label.join("\n")
  end
end

Building class

class Building
    attr_accessor :address_line1, :address_line2, :city, :state,
    :postal_code, :country
  def mailing_label
    label = []
    label << address_line1
    label << address_line2
    label << "#{city}, #{state} #{postal_code}"
    label << country
    label.join("\n")
  end
end


With module we can do
module Address
  attr_accessor :address_line1, :address_line2, :city, :state
    :postal_code, :country
   def mailing_label
      label = []
      label << address_line1
      label << address_line2
      label << "#{city}, #{state}  #{postal_code}"
      label << country
      label.join("\n")
    end
end

class User
  include Address
end

class Building
  include Address
end

As we can see module are included by module keyword. Classes use it by using include keyword.


Inheritance with Module Methods

When we include a module in a class, we are basically copying the instance methods into a class.
While when a module is extended inside of a class, all of the methods that are defined as basic methods get extended into the class, meaning that they are added as class methods.



- Reference: The Ruby Workshop: Peter Philips && Akshat Paul

Back to Home Page