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
Looked up https://www.relishapp.com/rspec/rspec-core/docs/helper-methods/define-helper-methods-in-a-module.
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.
Thanks to David Chelimsky for helping me with this :)
I have also found the following links very helpful from google:
http://blog.jayfields.com/2006/05/ruby-extend-and-include.html
http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/
http://rubyquicktips.com/post/1133877859/include-vs-extend
http://www.dan-manges.com/blog/27