Ada*_*sek 14 ruby inheritance ruby-on-rails ruby-on-rails-3.1
从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}
Run Code Online (Sandbox Code Playgroud)
但使用class_attribute
子类会污染他们的父母:
Presenter::Base => {:user => User, :person => Person}
Run Code Online (Sandbox Code Playgroud)
这根本不是理想的行为.是否有其他类型的访问器行为正确,或者我是否需要完全切换到另一种模式?我应该如何复制相同的行为class_inheritable_accessor
?
ben*_*sie 10
class_attribute
如果按预期使用,则不会污染其父母.确保您没有就地更改可变项目.
types_and_classes.keys.each do |t|
self.presented = presented.merge({t => types_and_classes[t]})
end
Run Code Online (Sandbox Code Playgroud)