【问题标题】:How to override methods stated in the scope of a class?如何覆盖类范围内的方法?
【发布时间】:2012-10-28 13:45:49
【问题描述】:

我正在使用 Ruby 1.9.2 和 Ruby on Rails 3.2.2。我有以下陈述:

class Category < ActiveRecord::Base
  include Commentable

  acts_as_list :scope => 'category_comment_id'

  has_many :comments, :class_name => 'CategoryComment'

  # ...
end

module Commentable
  extend ActiveSupport::Concern

  included do
    acts_as_list :scope => 'comment_id'

    has_many :comments, :class_name => 'Comment'

    # Other useful method statements...
  end

  # Other useful method statements...
end

在上面的代码中,我试图覆盖 acts_as_somethinghas_many 通过包含 Commentable 模块添加到 Category 类的方法。这两种方法都被声明为“在”Category 的范围内,所以上面的代码没有按预期工作:方法没有被覆盖。

是否可以覆盖这些方法?如果有,怎么做?

【问题讨论】:

  • 尝试将您的模块包含在课程的末尾。就像现在一样,模块中的方法被类自己的定义覆盖。
  • @Sergio Tulentsev - 在整个代码中依赖语句“位置”是一种不好的做法吗?
  • @user12882 不一定,但是 is 可能是不好的做法来定义一个方法(或范围——最终是一个方法)知道你想使用超类中的版本/module 代替。如果它永远不会被使用,为什么还要定义它?
  • @Sergio Tulentsev - 此外,我试图覆盖模块添加的特定方法,而不是相反。也就是说,给定一个向类添加方法的模块,我想覆盖该类中的一些方法。
  • @user12882 这不是现在发生的事情吗?

标签: ruby-on-rails ruby methods scope overriding


【解决方案1】:

您应该在类定义的末尾包含您的模块。就像现在一样,模块中的方法在类定义其方法之前被注入。之所以如此,是因为 ruby​​ 以自上而下的方式处理和评估代码。因此,稍后它会遇到类自己的方法定义并覆盖那些来自模块的方法。

因此,根据您的意图使用这些知识:谁应该覆盖谁。如果模块中的方法应该优先于类中的方法,请将其包含在最后。

编辑

鉴于此代码

require 'active_support/core_ext'

class Base
  def self.has_many what, options = {}
    define_method "many_#{what}" do
      "I am having many #{what} with #{options}"
    end
  end
end

module Commentable
  extend ActiveSupport::Concern

  included do
    has_many :comments, class_name: 'Comment'
  end
end

然后

class Foo < Base
  include Commentable
  has_many :comments
end

# class overrides module
Foo.new.many_comments # => "I am having many comments with {}"

class Foo < Base
  has_many :comments
  include Commentable
end

# module overrides class 
Foo.new.many_comments # => "I am having many comments with {:class_name=>\"Comment\"}"

【讨论】:

  • 您知道一个很好的资源,我可以在其中阅读/了解您在回答中提到的 Ruby 自上而下处理的更多信息吗?
  • @user12882:不是我的想法。我在某本书上读过。
猜你喜欢
  • 1970-01-01
  • 2014-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-27
  • 2016-09-18
相关资源
最近更新 更多