我正在使用 Ruby on Rails v3.2.2。在一个模块中,我试图“动态”打开一个类,以便向它添加一个使用局部变量的 Ruby on Rails“范围方法”,这样:
module MyModule
extend ActiveSupport::Concern
included do
# Note: The `CLASS_NAME` is not the class where `MyModule` is included. That
# is, for instance, if the including class of `MyModule` is `Article` then
# the `CLASS_NAME` is `User`.
CLASS_NAME = self.get_class_name.constantize # => User
counter_cache_column = self.get_counter_cache # => "counter_count"
class CLASS_NAME
def self.order_by_counter
order("#{counter_cache_column} DESC")
end
end
end
end
如果我运行上面的代码,我会收到以下错误:
NameError
undefined local variable or method `counter_cache_column' for #<Class:0x0000010775c558>
发生这种情况是因为counter_cache_column
in 未在模块的上下文中调用。我应该如何正确说明order_by_counter
范围方法?
奖励:您对上述“如此动态”的实施有何建议?