用继承覆盖类变量

时间:2018-01-10 17:31:43

标签: ruby

我的班级工厂看起来像这样:

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是唯一的,但显然情况并非如此。

有没有办法使用继承方法更改单个后代的类实例变量?或者我在这里做错了什么?

0 个答案:

没有答案