【问题标题】:Make ClassMethods also available as module function with ActiveSupport::Concern使用 ActiveSupport::Concern 使 ClassMethods 也可用作模块函数
【发布时间】:2011-09-30 23:14:50
【问题描述】:

给定以下代码:

module Foo
  extend ActiveSupport::Concern

  module ClassMethods
    def foo
      puts 'foo'
    end
  end
end

class Bar
  include Foo
end

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

【问题讨论】:

    标签: ruby-on-rails ruby activesupport


    【解决方案1】:

    这似乎是一种代码异味。话虽如此,您可以让 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
    

    【讨论】:

    • 效果很好,谢谢!顺便说一句,您为什么认为代码有异味?
    • 让一个模块从一个定义为它的类方法的模块中扩展自己似乎并不正确。通常,如果您想从 Foo 访问 foo 方法,您只需执行Foo::ClassMethods.foo。它并没有什么“错误”,但这不是我以前见过的模式,也不建议养成这种习惯。
    • @Beerlington:您确定这在第一个示例中有效吗Foo::ClassMethods.foo?我刚刚测试过,但没有(Ruby v2.0)。谢谢。
    猜你喜欢
    • 2013-02-01
    • 1970-01-01
    • 2012-01-30
    • 2013-12-20
    • 1970-01-01
    • 2014-04-28
    • 2011-09-05
    • 1970-01-01
    • 2012-10-18
    相关资源
    最近更新 更多