我是Rails 5/Spree 4的新手,但是我不能让回调在我的模型中工作。我想在狂欢中创建一个产品后运行一些方法,但我不理解这些对我来说完全陌生的included do东西。
型号:app/models/spree/product_decorator.rb
require 'active_support/concern'
module Spree
module ProductDecorator
extend ActiveSupport::Concern
included do
after_create :assign_prototype
end
def assign_prototype
binding.pry
end
end
end我想我忽略了一些愚蠢的事情,但我已经花了一个小时来处理这个问题。为什么这里不能识别after_create方法?
发布于 2020-03-27 16:18:11
这是给定in the docs的实际示例
module MyStore
module Spree
module ProductDecorator
def some_method
...
end
end
end
end
::Spree::Product.prepend MyStore::Spree::ProductDecorator正如你所看到的,如果你不在你的模块中包含/前置::Spree::Product,实际上什么都不会发生。您还应该将您的代码放在您自己的模块中,这样就不会损坏现有的Spree::ProductDecorator。
included do
# ...
end和施普雷没有任何关系。它全部是ActiveSupport::Concern,并封装了这个常见的Ruby惯用法:
module Spree
module ProductDecorator
def self.included(base)
base.class_eval do
after_create :assign_prototype
end
end
def assign_prototype
binding.pry
end
end
endModule#included是一个内置在Ruby中的钩子,当一个模块包含在一个类中时,它可以让你在这个类的上下文中执行代码。这就是你如何做访问器,验证,回调等,或者你通常在模块混合中的模型类主体中做的任何事情。
https://stackoverflow.com/questions/60881652
复制相似问题