How can I set some instance variables when extending a instance in the same way it can be done when creating it, with initialize.
In this example the variable set when extending is "lost":
module Mod
def self.extended(base)
@from_module = "Hello from Mod"
puts "Setting variable to: #{@from_module}"
end
def hello_from_module
return @from_module
end
end
class Klass
def initialize
@from_class = "Hello from Klass"
end
def hello_from_class
return @from_class
end
end
klass = Klass.new #=> #<Klass:0x00000000ed8618 @from_class="Hello from Klass">
klass.extend(Mod) #=> #<Klass:0x00000000ed8618 @from_class="Hello from Klass">
"Setting variable to: Hello from Mod"
klass.hello_from_class #=> "Hello from Klass"
klass.hello_from_module #=> nil (warning: instance variable @from_module not initialized)
Mod, soselfisModand the instance variable is an instance variable ofMod.returnis implicit in Ruby, the last thing left on the stack is the return value by default, so it can usually be omitted if the last thing in the method is what you want as a return value.