tags:

views:

1380

answers:

2

Just getting my head around Ruby metaprogramming... the mixin/modules always manage confuse me everytime.

  • include : mixes in specified module methods as instance methods in the target class
  • extend : mixes in specified module methods as class methods in the target class

So is the major difference just this or is a bigger dragon lurking? e.g.

module ReusableModule
  def module_method
    puts "Module Method: Hi there!"
  end
end

class ClassThatIncludes
  include ReusableModule
end
class ClassThatExtends
  extend ReusableModule
end

puts "Include"
ClassThatIncludes.new.module_method       # "Module Method: Hi there!"
puts "Extend"
ClassThatExtends.module_method              # "Module Method: Hi there!"
+4  A: 

That's correct.

Behind the scenes, include is actually an alias for append_features, which (from the docs):

Ruby's default implementation is to add the constants, methods, and module variables of this module to aModule if this module has not already been added to aModule or one of its ancestors.

Toby Hede
+8  A: 

What you have said is correct. Howver there is more to it than that.

If you have a class Foo and module Bar, including Bar in Foo gives instances of Foo access to objects to Bar's methods. Or you can extend Foo with Bar giving the class Foo access to Bar's methods. But also you can extend an arbitrary object with o.extend Bar. In this case the individual object gets Bar's methods even though all other objects with the same class as o do not.

domgblackwell
is it possible in rails to write a module which can extend user class and reload every time in development environment of rails.
T.Raghavendra