如何使用 ActiveSupport::Concern继承类方法



我的Ruby on Rails应用程序中有一个小的类层次结构。我试图通过一些我希望子类继承的信息来描述类的支持添加关注。这个问题可以用这个小样本来说明:

module Translatable
  extend ActiveSupport::Concern
  included do
  end
  module ClassMethods
    def add_translatable_fields(field_and_types)
      @translatable_fields ||= {}
      @translatable_fields.merge! field_and_types
    end
    def translatable_fields
      @translatable_fields
    end
  end
end
class Item
  include Translatable
  add_translatable_fields({name: :string})
end
class ChildItem < Item
end
class AnotherItem < Item
  add_translatable_fields({description: :text})
end
puts "Item => #{Item.translatable_fields.inspect}"
puts "ChildItem => #{ChildItem.translatable_fields.inspect}"
puts "AnotherItem => #{AnotherItem.translatable_fields.inspect}"

我希望返回此示例代码

Item => {name: :string}
ChildItem => {name: :string}
AnotherItem => {name: :string, description: :text}

但不幸的是,ChildItem 和 OtherItem 没有添加在父类上设置的类"属性",而是返回

Item => {name: :string}
ChildItem => nil
AnotherItem => {description: :text}

如何使类继承按照我想要的方式工作?

看起来子类是从父类正确继承的,但问题是类变量

我敢打赌你能做到

class ChildItem < Item
  add_translatable_fields(Item.translatable_field)
end

但我刚刚了解了这些 Rails 助手,它似乎更像是你正在寻找的。

http://api.rubyonrails.org/classes/Class.html#method-i-class_attribute

您可以在包含的块中定义class_attribute,它应该按照您希望的方式继承给所有子级。

最新更新