gpt4 book ai didi

ruby-on-rails - 重新打开 gem 提供的 ActiveRecord 模型

转载 作者:行者123 更新时间:2023-12-03 16:06:21 25 4
gpt4 key购买 nike

我正在尝试扩展 gem ( https://github.com/peteonrails/vote_fu ) 提供给我的应用程序的 ActiveRecord 模型 ( Vote )。 (即 vote.rb 中没有 app/models )

我的第一种方法是创建一个名为 lib/extend_vote.rb 的文件。包含代码:

Vote.class_eval do
after_create :create_activity_stream_event
has_one :activity_stream_event

def create_activity_stream_event
# something..
end
end

这在创建第一个投票时有效,但是当我尝试创建每个后续投票时,我收到错误 TypeError (can't dup NilClass) .

我认为这个错误是由 Vote 引起的。每次请求后都会自动重新加载类,但 lib/extend_vote.rb 中的代码服务器启动时只加载一次,这会导致 has_one :activity_stream_event协会行为怪异。 (此外,如果我在 config.cache_classes = true 中设置 development.rb,问题就会消失)

为了解决这个问题,我尝试通过添加 to_prepare 来在每个请求上重新加载投票扩展。阻止我的 development.rb :
config.to_prepare do
load 'extend_vote.rb'
end

这解决了 (can't dup NilClass)问题,但现在每当我创建一个新投票时, create_activity_stream_event回调被调用一次。即,第一次投票调用它一次,第二次调用它两次,等等。所以它看起来像 to_prepare block 过于激进地重新加载扩展并添加重复的回调。

向此 Vote 添加方法和回调的最佳方式是什么?模型?

最佳答案

[更新:应该是防止模块在同一类中多次包含的正确解决方案]

相信你可以使用ActiveSupport::Concern防止模块被多次包含,导致回调多次调用。
请参见下面的示例:

module VotePatch
extend ActiveSupport::Concern

included do
after_create :create_activity_stream_event
has_one :activity_stream_event
end

module InstanceMethods
def create_activity_stream_event
#your code here
end
end

end

Vote.send(:include, VotePatch)

关于ruby-on-rails - 重新打开 gem 提供的 ActiveRecord 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10761059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com