I'm creating an anonymous module because I need it to be dynamic, but using class variables like in the example below doesn't work. I have this code:
class Filter
def self.mod(var)
# Creating anonymous module
m = Module.new do
def hello
puts @var
end
def self.var=(var)
@@var = var
end
def self.var
@@var
end
end
# Setting the class variable
m.var = var
m
end
end
f1 = Filter.mod("hello")
puts f1.var # => hello
f2 = Filter.mod("goodbye")
puts f2.var # => goodbye
puts f1.var # => goodbye
Why does f1 change when I assign to f2? I need each module to maintain its own variable values. Is there a way to circumvent this with anonymous / dynamic modules?
If I include the Filter in a class:
class Main
include Filter.mod("hello")
end
m = Main.new
puts m.hello # => nil
How do I access the @var variable?
@varandf1.varwon't change.