Created
August 25, 2016 04:53
-
-
Save kamal-github/b89802cc06b1fae85666fa0028b9526a to your computer and use it in GitHub Desktop.
Include this module to make your class instance variable accessible to subclass which doesn't declare that variable(ref - http://www.railstips.org/blog/archives/2006/11/18/class-and-instance-variables-in-ruby/)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ClassLevelInheritableAttributes | |
def self.included(base) | |
base.extend(ClassMethods) | |
end | |
module ClassMethods | |
def inheritable_attributes(*args) | |
@inheritable_attributes ||= [:inheritable_attributes] | |
@inheritable_attributes += args | |
args.each do |arg| | |
class_eval %( | |
class << self; attr_accessor :#{arg} end | |
) | |
end | |
@inheritable_attributes | |
end | |
def inherited(subclass) | |
@inheritable_attributes.each do |inheritable_attribute| | |
instance_var = "@#{inheritable_attribute}" | |
subclass.instance_variable_set(instance_var, instance_variable_get(instance_var)) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment