我的班级工厂看起来像这样:
class Base
def self.attributes=(**keyvals)
attr_accessor *@@attributes.keys
define_singleton_method(:default) { new(**keyvals) }
end
def self.attributes
@@attributes
end
def initialize(opts={})
opts.each do |k,v|
instance_variable_set("@#{k}", v)
end
end
end
用法如下:
# the game
class Game < Base
self.attributes = {
players: {} # Hash of Player instances, keyed by name
}
end
print Game.default.instance_variables
# => [:@player]
# a single tile
class Tile < Base
self.attributes = {
type: '',
data: {}
}
end
print Tile.default.instance_variables
# => [:@type, :@data]
# -----------------
# PROBLEM IS HERE:
# -----------------
print Game.default.instance_variables
# => [:@type, :@data]
问题是我在定义Game.attributes
时会覆盖Tile.attributes
。我期望从Tile
设置的类实例变量对于Tile
是唯一的,但显然情况并非如此。
有没有办法使用继承方法更改单个后代的类实例变量?或者我在这里做错了什么?