gpt4 book ai didi

ruby-on-rails - 如何在 Rails 3.1 中复制 class_inheritable_accessor 的行为?

转载 作者:数据小太阳 更新时间:2023-10-29 06:38:10 25 4
gpt4 key购买 nike

从 Rails 3.1 开始,class_inheritable_accessor 产生弃用警告,告诉我改用 class_attribute。但是 class_attribute 以一种重要的方式表现不同,我将展示这一点。

class_inheritable_attribute 的典型用途是演示者类,如下所示:

module Presenter
class Base
class_inheritable_accessor :presented
self.presented = {}

def self.presents(*types)
types_and_classes = types.extract_options!
types.each {|t| types_and_classes[t] = t.to_s.tableize.classify.constantize }
attr_accessor *types_and_classes.keys
types_and_classes.keys.each do |t|
presented[t] = types_and_classes[t]
end
end
end
end

class PresenterTest < Presenter::Base
presents :user, :person
end

Presenter::Base.presented => {}
PresenterTest.presented => {:user => User, :person => Person}

但是使用class_attribute,子类会污染他们的父类:

Presenter::Base => {:user => User, :person => Person}

这根本不是我们想要的行为。是否有另一种类型的访问器以正确的方式运行,或者我是否需要完全切换到另一种模式?我应该如何在没有 class_inheritable_accessor 的情况下复制相同的行为?

最佳答案

如果按预期使用,

class_attribute 不会污染其父级。确保您没有就地更改可变项目。

types_and_classes.keys.each do |t|
self.presented = presented.merge({t => types_and_classes[t]})
end

关于ruby-on-rails - 如何在 Rails 3.1 中复制 class_inheritable_accessor 的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6617769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com