简体   繁体   English

如何在Ruby on Rails中从Gem向现有模型添加多态关联?

[英]How to add a polymorphic association to an existing model from a Gem in Ruby on Rails?

Suppose I have included a gem called acts_as_locatable in my project with an ActsAsLocatable::Location class defined within it. 假设我在我的项目中包含了一个名为acts_as_locatable的gem,其中定义了ActsAsLocatable::Location类。 I want to add a polymorphic :subject association to this class, which could be accomplished by simply editing the class in the gem to add the association, like this: 我想在这个类中添加一个多态:subject关联,这可以通过简单地编辑gem中的类来添加关联来实现,如下所示:

module ActsAsLocatable

  class Location < ::ApplicationRecord

    belongs_to :subject, polymorphic: true

    ...

  end

end

But this is a bad idea since I don't want to have to maintain this change with each update of the gem. 但这是一个坏主意,因为我不希望每次更新gem时都要保持这种变化。 Forking the Gem and modifying the fork also suffers from this same problem. 分叉Gem并修改fork也会遇到同样的问题。

How can I extend, decorate or otherwise augment this class to add a polymorphic :subject association without editing the model file in the gem, while leaving the rest of the functionality of the gem undisturbed? 如何扩展,修饰或以其他方式扩充此类以添加多态:subject关联而无需在gem中编辑模型文件,同时保持gem的其余功能不受干扰?

After doing a bit more research about monkey patching, it seems that one solution is to add an initializer (such as <root>/config/initializers/acts_as_locatable.rb ): 在对猴子补丁进行更多研究之后,似乎有一个解决方案是添加一个初始化器(例如<root>/config/initializers/acts_as_locatable.rb ):

ActsAsLocatable::Location.class_eval do
  belongs_to      :subject,           polymorphic: true
end

Is this the best option? 这是最好的选择吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM