在Ruby或Rails中,为什么有时在课堂上"包括",有时候在课堂外?

nop*_*ole 12 ruby module ruby-on-rails mixins

我想

class ApplicationController < ActionController::Base
  include Foo
Run Code Online (Sandbox Code Playgroud)

是添加"mixin" - 以便将Foo模块中的所有方法都视为ApplicationController的方法.

但现在我看到了代码

include Bar

class ApplicationController < ActionController::Base
  include Foo
Run Code Online (Sandbox Code Playgroud)

那为什么它在外面ApplicationController呢?这与将其置于其中的更常见用途ApplicationController有何不同?

sep*_*p2k 17

是的,include Foo在类中添加Foo了该类的祖先,从而使所有Foo的实例方法可用于这些类的实例.

任何类定义之外include Foo都会添加Foo到祖先的中Object.也就是说,就像你include FooObject类的定义中所做的一样.这样做的用途是所有Foo的实例方法现在都可用.