1

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?

6
  • Fixed code formatting a bit :) Commented Jul 13, 2015 at 13:28
  • This is different from what I understood from your comments in that other question. Just use @var and f1.var won't change. Commented Jul 13, 2015 at 13:34
  • I didn't really know how to ask it, what am I looking for? A dynamic module? I updated the example. I'm trying to avoid values being changed on all instances. Commented Jul 13, 2015 at 14:07
  • Perhaps, show your exact use-case and not a made-up one? Why do [you think] you need this module thing at all? Commented Jul 13, 2015 at 14:13
  • 1
    chat.stackoverflow.com/rooms/83135/… Commented Jul 13, 2015 at 14:50

2 Answers 2

1

The @@ defines a class variable on Filter, not on your new Module like you expect. You can see it with:

puts Filter.class_variables.inspect
# [:@@var]

This only exists once, and gets written to by every reference to @@var that happens in the scope of Filter.

What you really want is class instance variables on each of your Module.news, which you do with just a single @. This defines @var on your new instance of the Module class.

  def self.var=(var)
    @var = var
  end

  def self.var
    @var
  end

# ...

puts f1.class
# Module
puts f1.instance_variables.inspect
# [:@var]

puts f2.var
# goodbye
puts f1.var
# hello
Sign up to request clarification or add additional context in comments.

Comments

0

Because you assign to @@var which is a class variable. Try changing it to @var.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.