D
dreamcat four
Hi,
I'm having trouble understanding why this isn't available from the Ruby core?
Does core not provide an alternative / satisfactory implementation of this?
# clia.rb - Class Level Inheritable Attributes
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
class Polygon
include ClassLevelInheritableAttributes
inheritable_attributes :sides
@sides = 8
end
puts Polygon.sides # => 8
class Octogon < Polygon; end
puts Polygon.sides # => 8
puts Octogon.sides # => 8
Ref: http://railstips.org/2006/11/18/class-and-instance-variables-in-ruby
Its rather difficult to believe we must in each case define / require
our own custom module. Please note - i'm not complaining here. I just
want to know whether the above example is "the best solution in use"
for 1.8... 1.9....
Best regards,
dreamcat4
(e-mail address removed)
I'm having trouble understanding why this isn't available from the Ruby core?
Does core not provide an alternative / satisfactory implementation of this?
# clia.rb - Class Level Inheritable Attributes
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
class Polygon
include ClassLevelInheritableAttributes
inheritable_attributes :sides
@sides = 8
end
puts Polygon.sides # => 8
class Octogon < Polygon; end
puts Polygon.sides # => 8
puts Octogon.sides # => 8
Ref: http://railstips.org/2006/11/18/class-and-instance-variables-in-ruby
Its rather difficult to believe we must in each case define / require
our own custom module. Please note - i'm not complaining here. I just
want to know whether the above example is "the best solution in use"
for 1.8... 1.9....
Best regards,
dreamcat4
(e-mail address removed)