Skip to content

Instantly share code, notes, and snippets.

@kamal-github
Created August 25, 2016 04:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamal-github/b89802cc06b1fae85666fa0028b9526a to your computer and use it in GitHub Desktop.
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/)
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