【问题标题】:Ruby class instance variables in subclasses子类中的 Ruby 类实例变量
【发布时间】:2015-08-13 05:20:19
【问题描述】:

依靠this answer,我写了下面的类。使用时报错:

在“序列化”中:nil:NilClass (NoMethodError) 的未定义方法“[]=”。

如何访问基类中的变量@serializable_attrs?

基类:

# Provides an attribute serialization interface to subclasses.
class Serializable
    @serializable_attrs = {}

    def self.serialize(name, target=nil)
        attr_accessor(name)
        @serializable_attrs[name] = target
    end

    def initialize(opts)
        opts.each do |attr, val|
            instance_variable_set("@#{attr}", val)
        end
    end

    def to_hash
        result = {}
        self.class.serializable_attrs.each do |attr, target|
            if target != nil then
                result[target] = instance_variable_get("@#{attr}")
            end
        end
        return result
    end
end

用法示例:

class AuthRequest < Serializable
    serialize :company_id,      'companyId'
    serialize :private_key,     'privateKey'
end

【问题讨论】:

    标签: ruby oop syntax class-variables


    【解决方案1】:

    类实例变量不被继承,所以行

    @serializable_attrs = {}
    

    只在Serializable 中设置它而不是它的子类。虽然您可以使用继承的钩子在子类化上设置它或更改 serialize 方法来初始化 @serializable_attrs 我可能会添加

    def self.serializable_attrs
      @serializable_attrs ||= {}
    end
    

    然后使用它而不是直接引用实例变量。

    【讨论】:

    • 很高兴您建议的方法初始化并返回值。
    • 我发现的另一件好事:ActiveSupport 的class_attribute 函数(在active_support/core_ext/class/attribute 中)。
    • 如果您使用的是 Rails,那么这是一个很好的解决方案(注意不要无意中更新了属性)
    • 我在没有 Rails 的情况下使用它。
    猜你喜欢
    • 2013-03-24
    • 2014-09-21
    • 2013-11-26
    • 2014-10-23
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 2013-01-10
    相关资源
    最近更新 更多