Skip to content

Instantly share code, notes, and snippets.

@fantactuka
Created December 17, 2011 09:56
Show Gist options
  • Save fantactuka/1489828 to your computer and use it in GitHub Desktop.
Save fantactuka/1489828 to your computer and use it in GitHub Desktop.
Inheritable class attributes
module InheritableAttributes
def self.included base
base.extend ClassMethods
end
module ClassMethods
def inheritable_attr *attrs
attrs.each do |attr|
class_eval <<-CODE
def self.#{attr} #{attr}=nil
@#{attr} = #{attr} unless #{attr}.nil?
@#{attr}
end
CODE
end
@inheritable_attrs ||= [:inheritable_attrs]
@inheritable_attrs += attrs
end
def inherited subclass
@inheritable_attrs.each do |attr|
subclass.instance_variable_set("@#{attr}", instance_variable_get("@#{attr}"))
end
end
end
end
module Foo
class Bar
include InheritableAttributes
inheritable_attr :platform
platform "desktop"
end
class Baz < Bar
end
class Tar < Baz
platform "mobile"
end
class Cat < Baz
end
end
puts Foo::Bar.platform
puts Foo::Baz.platform
puts Foo::Tar.platform
puts Foo::Cat.platform
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment