使用 Ruby 3.1.1。
嘗試實作類似于:https ://github.com/mongodb/mongoid/blob/master/lib/mongoid/fields.rb :: class_attribute :fields
當我在父模型中包含模型關注點時,class_attributes 似乎會合并到子模型中。我想在每個子類上維護一個單獨的 class_attribute 散列,就像 mongoid Field 關注點一樣。
這似乎只在繼承時發生。
module Dashboardable
extend ActiveSupport::Concern
included do
class_attribute :dashboard_fields
self.dashboard_fields = {}
end
class_methods do
def dashboard_field(name, options = {})
dashboard_fields[name] = options.merge(klass: self)
end
end
end
class Person
include Mongoid::Document
include Dashboardable
dashboard_field :first_name
end
class Foo < Person
dashboard_field :foot
field :foot, type: String
end
class Bar < Person
dashboard_field :bart
field :bart, type: String
end
Foo.dashboard_fields: [:first_name, :foot]
Bar.dashboard_fields: [:first_name, :foot, :bart]
Foo.fields: ["_id", "_type", "foot"]
Bar.fields: ["_id", "_type", "bart"]
uj5u.com熱心網友回復:
我進行了很多編輯和一些挖掘,以找出問題和發生了什么。對不起。
發生的事情是class_attribute所有類實際上在它們的實體屬性中共享相同的物件。這是一種預期的行為。
class_attribute如果您確保每個子類都獲得“父哈希”的副本,您實際上可以使用它:
module Dashboardable
extend ActiveSupport::Concern
included do
class_attribute :dashboard_fields, default: {}
end
class_methods do
def inherited(subclass)
subclass.class_eval { self.dashboard_fields = superclass.dashboard_fields.dup }
end
def dashboard_field(name, options = {})
dashboard_fields[name] = options.merge(klass: self)
end
end
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/459987.html
下一篇:如何在不宣告ServletContextEvent類的物件的情況下使用事件變數來呼叫方法getServletContext?
