Hi guys!!!
My question is:
Is any way to define variables in module which can be further used in
mixin? The problem is that module I wanted to include into class has
constant variables defined which are used within function it implements.
I’m looking for simplest way to overwrite the variables from the class
(may change the variables to non constant ones) the same meaning not to
change implementation of functions from the module. See:
module Mod
AnyVar = 10
def func
#the method use AnyVar
end
end
class MyClass
include Mod
def initialize
#read configuration
#how to make the function use new AnyVar value without changing its
implementation and parameters list
func()
end
end
Thanks a lot for any ideas.
I don’t know if I get the point but this seems work:
module Mod
@anyvar = 10
def func
puts @anyvar
end
end
class MyClass
include Mod
def initialize
#read configuration
@anyvar = 2
func()
end
end
MyClass.new
=> 2
Yep, you’re my hero
Works well.
Hi –
On Tue, 29 Apr 2008, Sandro P. wrote:
I don’t know if I get the point but this seems work:
module Mod
@anyvar = 10
def func
puts @anyvar
end
end
You’ve got two variables called @anyvar in that code, and they have no
relation to each other.
The first one is an instance variable belonging to the module Mod
(that is, the actual object Mod). The second one represents an
instance variable that will belong to each object that executes the
func method.
So the @anyvar = 10 line is serving no purpose.
David
Well, maybe you can try this way…
module Mod
def Mod.included(mod)
mod.class_eval <<-EOS
alias_method :old_initialize, :initialize
def initialize
@anyvar = 10
old_initialize
end
EOS
end
def func
puts @anyvar
end
end
class MyClass
def initialize
#read configuration
puts @anyvar
@anyvar = 2
func()
end
include Mod
end
MyClass.new
=> 10
=> 2
Marcin T. wrote:
module Mod
def initialize
I am not sure I quite understand what you are trying to do, but you can
do something like this:
module A
def initialize
super
@var = 1
end
end
class B
include A
def initialize
super
end
def check_var
puts @var
end
end
B.new.check_var #=> 1
The trouble is you need to make sure you call ‘super’ religiously if you
are including a lot of modules.
-Justin