ruby-on-rails - 使用 ActiveSupport::Concern 使 ClassMethods 也可用作模块函数

标签 ruby-on-rails ruby activesupport

给出以下代码:

module Foo
  extend ActiveSupport::Concern

  module ClassMethods
    def foo
      puts 'foo'
    end
  end
end

class Bar
  include Foo
end

我想做的是调用 Foo.foo 而不是 Bar.foo。有时在原始模块上调用类方法感觉更自然,特别是当功能与包含的类无关并且与原始模块名称一起更好地描述时。

最佳答案

这看起来像是代码味道。话虽如此,您可以让 Foo 模块使用类方法扩展自身:

module Foo
  extend ActiveSupport::Concern

  module ClassMethods
    def foo
      puts 'foo'
    end
  end

  extend ClassMethods
end

class Bar
  include Foo
end

Bar.foo
Foo.foo

关于ruby-on-rails - 使用 ActiveSupport::Concern 使 ClassMethods 也可用作模块函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6619624/

相关文章:

ruby-on-rails - Rails 不会为主键使用序列?

ruby-on-rails - 创建客户时 strip 错误 : You passed an empty string for 'card'

ruby-on-rails - 如何重定向到特定 Controller ?

ruby - 如何为 Dashing 启用 redis?

ruby-on-rails - 如何使用 has_many :through association? 为所有者和成员建模

ruby-on-rails - 如何使用带有西里尔字母的 ActiveSupport::Inflector

javascript - Ruby on Rails 中的 morris.js 错误

ruby-on-rails - 使用 ActiveRecord 在数据库中存储记录的长时间运行的 ruby​​ 进程

internet-explorer - 这是对微软关于支持 IE6 的声明的正确解释吗?

ruby-on-rails - 为什么 Rails 的 `HashWithIndifferentAccess` 将键存储为字符串而不是符号?