【发布时间】: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_something 和 has_many 通过包含 Commentable 模块添加到 Category 类的方法。这两种方法都被声明为“在”Category 的范围内,所以上面的代码没有按预期工作:方法没有被覆盖。
是否可以覆盖这些方法?如果有,怎么做?
【问题讨论】:
-
尝试将您的模块包含在课程的末尾。就像现在一样,模块中的方法被类自己的定义覆盖。
-
@Sergio Tulentsev - 在整个代码中依赖语句“位置”是一种不好的做法吗?
-
@user12882 不一定,但是 is 可能是不好的做法来定义一个方法(或范围——最终是一个方法)知道你想使用超类中的版本/module 代替。如果它永远不会被使用,为什么还要定义它?
-
@Sergio Tulentsev - 此外,我试图覆盖模块添加的特定方法,而不是相反。也就是说,给定一个向类添加方法的模块,我想覆盖该类中的一些方法。
-
@user12882 这不是现在发生的事情吗?
标签: ruby-on-rails ruby methods scope overriding