如何在Rails 3.1中复制class_inheritable_accessor的行为? [英] How do I replicate class_inheritable_accessor's behavior in Rails 3.1?
问题描述
从Rails 3.1开始, class_inheritable_accessor
产生弃用警告,告诉我改为使用 class_attribute
。但是 class_attribute
的行为方式与我将演示的重要方式不同。
Beginning with Rails 3.1, class_inheritable_accessor
produces deprecation warnings, telling me to use class_attribute
instead. But class_attribute
behaves differently in an important way which I will demonstrate.
class_inheritable_attribute
将是一个演示者类,如下所示:
A typical use of class_inheritable_attribute
would be a presenter class, like so:
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
,子类将污染他们的父母:
But using class_attribute
, subclasses will pollute their parents:
Presenter::Base => {:user => User, :person => Person}
这根本不是所希望的行为。是否有其他类型的访问器行为正确,或者我是否需要完全切换到另一种模式?如果没有 class_inheritable_accessor
,我应该如何复制相同的行为?
Which is not desired behavior at all. Is there another type of accessor that behaves the correct way, or do I need to switch to another pattern altogether? How should I replicate the same behavior without class_inheritable_accessor
?
推荐答案
class_attribute
如果按预期使用,则不会污染其父级。确保你没有就地改变可变项。
class_attribute
won't pollute its parent if it's used as intended. Make sure you're not changing the mutable items in-place.
types_and_classes.keys.each do |t|
self.presented = presented.merge({t => types_and_classes[t]})
end
这篇关于如何在Rails 3.1中复制class_inheritable_accessor的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!