Filipe Freire
Filipe Freire

Reputation: 833

How to keep a Set between instances of an ActiveRecord?

I have an ActiveRecord class that multiple classes inherit.

The class has a method:

def self.doSomeEvaluation(*args)
  #do some evaluation
end

I want to save and add in a Set the arguments of each call to doSomeEvaluation for each subclass. I also want this to be independent of the current instance of that subclass. This Set should be individual to each subclass of the ActiveRecord class and should be kept between different instances of that implemented subclass.

When I try to keep a set on the level of the doSomeEvaluation call, It's similar to this:

def self.doSomeEvaluation(*args)
  args.each do |arg|
    @set.add(arg)
    #do some evaluation
end

With this implementation, I fail to achieve such behavior, in the sense that between instances of a given subclass the Set's values are lost. I also tried to keep the set as a class variable, but I still can't achieve the behavior mentioned above:

def self.doSomeEvaluation(*args)
  args.each do |arg|
    @@set.add(arg)
  #do some evaluation
end

Also tried using an ActiveRecord attribute but it works as a constant and doesn't allow for this behavior.

Any ideas on how I can achieve this behavior? Is the behavior acceptable from a logical point of view?

Upvotes: 0

Views: 49

Answers (1)

Stan Mazhara
Stan Mazhara

Reputation: 826

You are close with your solution

def self.doSomeEvaluation(*args)
  @@set ||= {}
  @@set[self] ||= Set.new
  args.each { |arg| @@set[self] << arg }

  #do some evaluation
end

Since @@set is a class variable it is shared across all class instances which is what you want. But you also want to distinguish between different classes. For that you need to make it a hash that takes the current class (self) as a key.

Upvotes: 1

Related Questions