【问题标题】:ActiveSupport::Concern missing superActiveSupport::关注缺少超级
【发布时间】:2013-10-29 16:45:37
【问题描述】:

我有一个类 GoodsTransaction:

require Rails.root.join('lib','two_parties_transaction.rb')

class GoodsTransaction < Transaction

  include TwoPartiesTransaction

  def counterparty(org, loop = false)

    res = #Some logic
    res || super(org)
  end
end

其中包括 TwoPartiesTransaction 模块:

module TwoPartiesTransaction
  extend ActiveSupport::Concern

  included do
    def counterparty(org)
       #Some logic
    end
  end
end

运行交易对手失败:

muichkine@ubuntu:~/src/white$ rails c
Faraday::Builder is now Faraday::RackBuilder.
Loading development environment (Rails 4.0.0)
2.0.0p247 :001 > tr = GoodsTransaction.new
=> #<GoodsTransaction _id: 5264e2eb75627540dd000000, e(end_date): nil, p(span): nil, s(start_date): nil, u(span_unit): nil, _type: "GoodsTransaction", a(autobook): nil, c(forced_close): nil, d(public_id): nil, k(autobook_period): nil, l(label): nil, n(autobook_number): nil, t(autobook_until): nil, contact_ids: nil, parent_id: nil, fc(creditor): nil, fd(debtor): nil> 
2.0.0p247 :002 > tr.counterparty(nil)
NoMethodError: super: no superclass method `counterparty' for   #<GoodsTransaction:0x000000090fe1d8>
from /home/muichkine/src/white/app/models/transactions/goods_transaction.rb:148:in `counterparty'

我在做什么跳过超级 coutnerparty 方法?

【问题讨论】:

    标签: ruby-on-rails ruby activesupport


    【解决方案1】:

    要将模块中的实例方法包含到类中,您不需要使用ActiveSupport::Concern。你可以这样做

    module TwoPartiesTransaction
      def counterparty(org)
         # ...
      end
    end
    

    如果出于其他原因需要ActiveSupport::Concern,您仍然可以使用它,即在类级别执行代码(例如scope 等)或将类方法添加到包含类。有关ActiveSupport::Concernsee the API documentation 的更多详细信息。

    【讨论】:

    • 从您指向的文档中,我了解到 1/ ClassMethods 已扩展未包含在基类中,这不是我正在查看的内容。 2/ 文档根本没有谈到 ClassMethods 是强制性的,因为它们将代码直接放在 indluded do 块中。我错了吗?!
    • 1) 我同意这令人困惑,但extend 会将模块的实例方法添加为类方法。这不是你想要的吗? 2)我已经编辑了我的答案,也许这可以澄清一点。
    • 如果您碰巧希望模块方法作为包括模块在内的类中的实例方法,只需在模块中使用普通方法(而不是嵌套的ClassMethods
    • 好吧,1/ 我确实想要实例方法,所以我同意将它们放在 ClassMethods 中是没有意义的。 2/您的代码没有使用包含的 do 块,据我了解,这是 ActiveSupport::Concern 的基本原理。 3/将代码直接放在模块中而不包含 do 会引发错误,因为代码是在加载时而不是在包含时评估的。
    • 好的,现在你的问题的答案很简单。请查看我的编辑。
    猜你喜欢
    • 2011-01-27
    • 1970-01-01
    • 2015-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    • 1970-01-01
    相关资源
    最近更新 更多