HanXu
HanXu

Reputation: 5597

How to define instance variable through mixin

I'm writing a program like this:

module Filter
  def self.included?(klass)
    @count = 0
  end
end

class Object
  include Filter
end

class Person
  def get_count
    puts @count
  end
end

I want to define an instance variable @count through mixing Filter, hoping this mixin is accessible to all the Object.

However, my way doesn't work.

Can anyone tell me how to achieve this?

Upvotes: 2

Views: 126

Answers (2)

Anupam
Anupam

Reputation: 1530

@HanXu, The solution from Maurício Linhares (as well as the suggestion to not pollute the main namespace) is the ideal way to go.

However, if you are really looking to change every instance of Object, then you might be able to just open the Object class and add the specific functionality you are looking for:

class Object
  attr_accessor :count
end

...

p = Person.new
p.count = 10
puts p.count    # => 10

Not recommended, but will work (in any case, you are opening Object to include the module now.)

Upvotes: 0

Maurício Linhares
Maurício Linhares

Reputation: 40333

Don't use a variable, use an attribute:

module Counter
  attr_accessor :count
end

class Person
  include Counter
end

person = Person.new
person.count = 50
puts person.count

Also, don't include stuff into Object, only include in your classes. Polluting the main namespace with non-general methods is bad and could lead to method name clashes in other classes, causing hard-to-find bugs.

Only include modules where you think they're needed, not everywhere.

Upvotes: 2

Related Questions