Created
December 17, 2011 09:56
-
-
Save fantactuka/1489828 to your computer and use it in GitHub Desktop.
Inheritable class attributes
This file contains hidden or 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 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