Pages

Monday, December 05, 2011

Include versus extend

I found the following definition for both in http://marakana.com/bookshelf/ruby_tutorial/modules.html very helpful.
  • include - mixes in a module into the class' objects (instantiations)
  • extend - mixes in a module's into self and the module's methods are available as class methods

I have also posted the question which ultimately leads to finding out the differences between include and extend in the rspec google group.

I wrote a few test scripts to learn about this more.

Include - usage of method as an object method is successful


#!/usr/bin/ruby

module Helper
  def help
    'helper method is valid'
  end
end

class Baz
   include Helper
end

puts 'Calling the class method in a chain: ' + Baz.new.help.to_s # => :avalable

bazzer = Baz.new
puts 'Calling the class method within an object: ' + bazzer.help.to_s

Results

[amalthea]$ ./include.rb
Calling the class method in a chain: helper method is valid
Calling the class method within an object: helper method is valid


Never use 'include' in the object as it's invalid.
Here's what I meant:



#!/usr/bin/ruby


module Helper
  def help
     :available
  end
end


class Bar
end


bar = Bar.new
bar.include(Helper)  # <--  this is not valid.
bar.help


Extend

#!/usr/bin/ruby

module Helper
  def help
    'helper method is called'
  end
end

class Baz
   extend Helper
end

puts 'When called as a class method, it works and the string is received: ' + Baz.help.to_s

puts rescue Baz.new.help

Results

When called as a class method, it works and the string is received: helper method is called

From the script above, the call to the module's method, help does not work and throws an exception (which I have put in rescue to stop the script from failing) because when extend is used, the module's methods will only be available as a class methods.