Allow descending classes to inherit instance variables. This is useful for persisting class-level configuration.
Add this line to your application's Gemfile:
gem'inheritable_instance'Insert the InheritableInstance module into the ancestry chain of your class:
classFakeClassextendInheritableInstanceendThen use inheritable_instance to set any instance variables
that you want to be inherited by subclasses:
classFakeClassinheritable_instance:@thing_one,1inheritable_instance:@thing_two,2endThese variables will be automatically set on inheritance:
classDoubleFake < FakeClass;endDoubleFake.instance_variable_get(:@thing_one) == 1DoubleFake.instance_variable_get(:@thing_two) == 2It is convenient to pair this with the attr_* methods:
class << FakeClassattr_accessor:thing_twoendDoubleFake.thing_two="two"FakeClass.thing_two == 2DoubleFake.thing_two == "two"Note that the values are duplicated (when possible):
classOneTwoThreeextendInheritableInstanceinheritable_instance:@list,[]class << self;attr_reader:list;endendOneTwoThree.list << 1 << 2 << 3Abc=Class.new(OneTwoThree)Abc.list << 'a' << 'b' << 'c'Abc.list == [1,2,3,'a','b','c']OneTwoThree.list == [1,2,3]If for some reason it is inconvenient to extend the module,
there is an Includible helper that you can use instead:
classSameAsFakeClassincludeInheritableInstance::IncludibleendBug reports and pull requests are welcome on GitHub at https://github.com/fledman/inheritable_instance.
The gem is available as open source under the terms of the MIT License.