Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inherit class-level instance variables in Ruby?

I want a child class to inherit a class-level instance variable from its parent, but I can't seem to figure it out. Basically I'm looking for functionality like this:

class Alpha
  class_instance_inheritable_accessor :foo #
  @foo = [1, 2, 3]
end

class Beta < Alpha
  @foo << 4
  def self.bar
    @foo
  end
end

class Delta < Alpha
  @foo << 5
  def self.bar
    @foo
  end
end

class Gamma < Beta
  @foo << 'a'
  def self.bar
    @foo
  end
end

And then I want this to output like this:

> Alpha.bar
# [1, 2, 3]

> Beta.bar
# [1, 2, 3, 4]

> Delta.bar
# [1, 2, 3, 5]

> Gamma.bar
# [1, 2, 3, 4, 'a']

Obviously, this code doesn't work. Basically I want to define a default value for a class-level instance variables in the parent class, which its subclasses inherit. A change in a subclass will be the default value then for a sub-subclass. I want this all to happen without a change in one class's value affecting its parent or siblings. Class_inheritable_accessor gives exactly the behavior I want... but for a class variable.

I feel like I might be asking too much. Any ideas?

like image 831
wmjbyatt Avatar asked May 23 '12 22:05

wmjbyatt


People also ask

Are instance variables inherited in Ruby?

Instance variables are not inherited.

Can we inherit instance variables?

I know that instance variable are not inherited but they can be accessed in sub class. If they can be accessed in sub class then does that means that they are shared between super class and subclass or both super class and subclass have different copy.

Can a class method access instance variables Ruby?

class . There are no "static methods" in the C# sense in Ruby because every method is defined on (or inherited into) some instance and invoked on some instance. Accordingly, they can access whatever instance variables happen to be available on the callee.

What are class instance variables Ruby?

Used declare variables within a class. There are two main types: class variables, which have the same value across all class instances (i.e. static variables), and instance variables, which have different values for each object instance.


2 Answers

Rails has this built into the framework as a method called class_attribute. You could always check out the source for that method and make your own version or copy it verbatim. The only thing to watch out for is that you don't change the mutable items in place.

like image 85
Peter Brown Avatar answered Sep 22 '22 15:09

Peter Brown


What I did in my project for using resque is to define a base

class ResqueBase
  def self.inherited base
    base.instance_variable_set(:@queue, :queuename)
  end
end

In the other child jobs, the queue instance will be set by default. Hope it can help.

like image 21
Oscar Jiang Avatar answered Sep 23 '22 15:09

Oscar Jiang