Skip to content

Instantly share code, notes, and snippets.

@vjt
Created January 28, 2009 11:02
Show Gist options
  • Save vjt/53899 to your computer and use it in GitHub Desktop.
Save vjt/53899 to your computer and use it in GitHub Desktop.
# Adds class inheritable attributes to every class. See the examples for more information.
# Originally posted on http://pastie.org/39201 (9 February 2007)
#
require 'active_support'
class Class
def class_inheritable_attributes(*syms, &block)
eigenclass = class << self; self; end
syms.each do |sym|
eigenclass.send :define_method, sym do |*values|
if value = values.first
value = block.call value if block
write_inheritable_attribute sym, value
else
read_inheritable_attribute sym
end
end
class_eval <<-EOS
def #{sym}
self.class.read_inheritable_attribute :#{sym}
end
EOS
end
end
alias :class_inheritable_attribute :class_inheritable_attributes
end
class Base
class_inheritable_attribute(:root) { |root| Pathname.new(root).realpath }
end
class A < Base
root '.'
end
>> Base.root
=> nil
>> a = A.new
=> #<A:0xb78a2c64>
>> a.root
=> #<Pathname:/home/vjt/code/ecole/lib>
>> A.root
=> #<Pathname:/home/vjt/code/ecole/lib>
>> A.root '.'
=> #<Pathname:/home/vjt/code/ecole/lib>
>> A.root '..'
=> #<Pathname:/home/vjt/code/ecole>
# - [email protected]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment