Skip to content

Repository files navigation

InheritableInstance

Allow descending classes to inherit instance variables. This is useful for persisting class-level configuration.

Installation

Add this line to your application's Gemfile:

gem'inheritable_instance'

Usage

Insert the InheritableInstance module into the ancestry chain of your class:

classFakeClassextendInheritableInstanceend

Then use inheritable_instance to set any instance variables that you want to be inherited by subclasses:

classFakeClassinheritable_instance:@thing_one,1inheritable_instance:@thing_two,2end

These variables will be automatically set on inheritance:

classDoubleFake < FakeClass;endDoubleFake.instance_variable_get(:@thing_one) == 1DoubleFake.instance_variable_get(:@thing_two) == 2

It 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]

Additional Details

If for some reason it is inconvenient to extend the module, there is an Includible helper that you can use instead:

classSameAsFakeClassincludeInheritableInstance::Includibleend

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/fledman/inheritable_instance.

License

The gem is available as open source under the terms of the MIT License.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages