0

I have a class like the following:

class Foo
  @variable = {}

  class << self
    attr_accessor :variable
  end

  def self.run(file)
    # do stuff
  end
end

I have an RSpec type method like the following:

def method?
  Foo.variable[@name] = {}
  Foo.variable[@name][:variable_two] = 'string'

  true
end

I have an rspec and custom task like the following:

RSpec::Core::RakeTask.new("rspec-#{spec}".to_sym) do |task|
  task.pattern = spec
end

desc "do stuff"
task spec do
  Rake::Task["rspec-#{spec}".to_sym].invoke
  Foo.run(spec)
end

I am executing the spec task with rake.

If I do puts Foo.variable in the method? definition, then I see that during the RSpec subtask for "rspec-#{spec}".to_sym the Foo.variable hash is populated exactly and perfectly as I expect. However, as soon as Foo.run executes after the rspec rake task, the Foo.variable hash becomes empty. I have tried many different ways to transfer or retain the values generated during the rspec rake task to the Foo.run method and the above code is basically the template I return to after each attempt.

What kind of algorithm gives me the functionality to retain values assigned to a variable during a rspec rake task for another method executed afterwards?


Tried class variable suggestion with:

class Foo
  @@variable = {}

  def self.variable
    @@variable
  end

  def self.run(file)
    # do stuff
  end
end

and same problem.

Matthew Schuchard
  • 25,172
  • 3
  • 47
  • 67
  • That's a very peculiar definition for a class. Where's your `initialize` if you're using instances? If not, try using [`cattr_accessor`](http://stackoverflow.com/questions/3002247/cattr-accessor-outside-of-rails) to define it. – tadman Jun 23 '16 at 17:44
  • I have no instances for that class. I just googled the `cattr_accessor` since I have never heard of it and found out why: it is rails. This is just ruby. – Matthew Schuchard Jun 23 '16 at 19:28
  • If you have a class with no instances, ever, what you want is a `module` instead. `mattr_accessor` is similar to `attr_accessor` but for modules. These are in ActiveSupport, but stand-alone versions are also available. – tadman Jun 23 '16 at 19:29

1 Answers1

1

I think you might be looking for a class variable. Something along the lines of

class Foo
  @@bar = 0

  def increment
    @@bar += 1
  end

  def bar
    @@bar
  end
end

f = Foo.new
f.bar
=> 0

f.increment
f.bar
=> 1

g = Foo.new
g.bar
=> 1

g.increment
g.bar
=> 2

f.bar
=> 2

Class variables, denoted with the double @ (@@bar in this case), are generally considered bad practice, so please be careful when using them.

Justin Wood
  • 9,941
  • 2
  • 33
  • 46