为什么不推荐使用InstanceMethods模块?

Rob*_*bin 17 ruby-on-rails activesupport ruby-on-rails-3 ruby-on-rails-3.2

我喜欢ActiveSupport :: Concern.

通过良好的语法,可以轻松地为类添加功能.

无论如何,在Rails 3.2中,不推荐使用InstanceMethods模块.如果我理解正确,我们应该只在included块中定义我们的方法(实际上它只是在模块的主体中​​):

# edit: don't do this! The method definition should just be in the body of the module
included do
    def my_method; end
end
Run Code Online (Sandbox Code Playgroud)

我只是想知道是否有人知道他们为什么决定那样做?

Sim*_*tsa 27

让我们看看你首先链接的例子.

module TagLib
  extend ActiveSupport::Concern

  module ClassMethods
    def find_by_tags()
      # ...
    end
  end

  module InstanceMethods
    def tags()
      # ...
    end
  end 
end
Run Code Online (Sandbox Code Playgroud)

将TagLib包含到类中时AS关注会自动使用ClassMethods模块扩展类,并包含InstanceMethods模块.

class Foo
  include TagLib
  # is roughly the same as
  include TagLib::InstanceMethods
  extend TagLib::ClassMethods
end
Run Code Online (Sandbox Code Playgroud)

但是您可能已经注意到我们已经包含了TagLib模块本身,因此其中定义的方法已经可以作为类中的实例方法使用.为什么你想要一个单独的InstanceMethods模块呢?

module TagLib
  extend ActiveSupport::Concern

  module ClassMethods
    def find_by_tags()
      # ...
    end
  end

  def tags()
    # ...
  end
end

class Foo
  include TagLib
  # does only `extend TagLib::ClassMethods` for you
end
Run Code Online (Sandbox Code Playgroud)

  • 是的,我认为这是他们看过这个功能并且说"WTF!为什么我们这样做?"的那个时代之一.将方法放在InstanceMethods模块中是多余的.所以不,旧的方式和新的方式之间没有区别,只有一个不那么恒定的浮动. (6认同)