Ruby Modules, Mixins and name clashes

Ruby allows the creation of modules that provide namespaces for methods and constants to live. They are also used to mixin these methods and constants into classes. These mixed-in modules provide a class with references to whatever is defined within the module. Below is a small (meaningless) Ruby module.

module AnthonyModule
  CONST_DATA = "I am a constant from AnthonyModule"

  def who_am_i
    puts "My name is: #{@name}"
  end

  def ten_times write_me
    10.times { puts "#{write_me}" }
  end
end

This module provides two methods and one constant. When this module is mixed in with a class these methods will become instance methods of the class. Below is an example of using the require method to load the AnthonyModule.rb file and the include method to reference the module in the class.

require "AnthonyModule"

class MyClass
  include AnthonyModule

  def initialize name
    @name = name
  end

end

Notice this class does not have a method called ten_times defined in it. However when an instance of this class is created it will have a ten_times method because the AnthonyModule is included. A call to this method is shown below.

m = MyClass.new "Instance 1"
m.ten_times "Hello modules!"

This will produce ten lines each with “Hello modules!” printed on it. Now what happens if another module is introduced that provides another method also named ten_times?

module NewModule
  CONST_DATA = "I am a constant in newmodule.rb"

  def ten_times multiply_me
    puts "ten times #{multiply_me} is: #{ 10 * multiply_me }"
  end
end

Using require and include to mix in NewModule into the class there are now two methods with the same name and signature in the class. Because Ruby looks in the module included last in a class it will find the NewModule#ten_times method before the AnthonyModule#ten_times method. Running the sample code gives an error now.

ruby/NewModule.rb:5:in `*': String can't be coerced into Fixnum (TypeError)

The problem here is that Ruby does not know how to multiply a number by a string. I don't want to do this though, I want to print out my message ten times. Because I'm calling the ten_times method outside of the class I can't specify exactly which ten_times method I want to call. Ruby picks the first one it finds searching backwards (upwards) through the include list. It appears as though using mixed in methods with a name clash outside of the class can not be done. If the module's methods were called in some class methods the module name could be used to differentiate between which method should be called. Outside the class there is no such luck.

I'll be starting a Rails app later.

Anthony

0 comments ↓

There are no comments yet...Kick things off by filling out the form below.

Leave a Comment