【问题标题】:Override ActiveSupport::Concern in model覆盖模型中的 ActiveSupport::Concern
【发布时间】:2019-02-22 22:20:16
【问题描述】:

我有一个看起来像这样的问题:

module Foo
  extend ActiveSupport::Concern

  def bar
    puts "bar"
  end
end

其他三个模型使用该类方法,因为它们需要相同的东西。然后我有一个一次性模型,需要该方法来做其他事情。我有这样的设置:

class FooFoo < ApplicationRecord
  def self.bar
    puts "foo bar"
  end
end

现在,当我调用FooFoo.bar 时,它会打印“foo”而不是“foo bar”。如何覆盖关注点中定义的方法?我希望它只运行我的模型中定义的方法FooFoo,而不是关注的方法Foo。我看了一遍,但我认为我没有看到我需要的东西。一些帮助将不胜感激!

编辑:我也试过这个希望它会工作,但它没有:

class FooFoo < ApplicationRecord
  def FooFoo.bar # I used FooFoo.bar here instead of self.bar
    puts "foo bar"
  end
end

【问题讨论】:

    标签: ruby-on-rails activesupport-concern


    【解决方案1】:

    问题是您需要明确声明您希望bar 成为类方法...

    module Foo
      extend ActiveSupport::Concern
    
      class_methods do 
        def bar
          puts "bar"
        end
      end
    end
    

    现在,您可以覆盖它...

    class FooFoo < ApplicationRecord
      def self.bar
        puts "foo bar"
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2014-07-04
      • 2015-03-28
      • 1970-01-01
      • 2012-09-14
      • 2015-12-29
      • 1970-01-01
      • 2012-01-30
      • 2019-07-20
      • 1970-01-01
      相关资源
      最近更新 更多