在Ruby或Rails中,为什么要“包含"?有时在课堂上,有时在课堂外? [英] In Ruby or Rails, why is "include" sometimes inside the class and sometimes outside the class?
问题描述
我以为
class ApplicationController < ActionController::Base
include Foo
是添加一个"mixin"-以便Foo模块中的所有方法都被视为ApplicationController的方法.
is to add a "mixin" -- so that all methods in the Foo module are treated as methods of the ApplicationController.
但是现在我看到的是
include Bar
class ApplicationController < ActionController::Base
include Foo
那为什么在ApplicationController
之外呢?与将其放入ApplicationController
的更常见用法有何不同?
So why is it outside of ApplicationController
? How is that different from the more common use of putting it inside of ApplicationController
?
推荐答案
是的,类中的include Foo
将Foo
添加到该类的祖先,从而使所有Foo
的实例方法可用于这些实例的实例课.
Yes, include Foo
inside a class adds Foo
to that class's ancestors and thus makes all of Foo
's instance methods available to instances of those class.
在任何类定义include Foo
之外,会将Foo
添加到Object
的祖先. IE.它与在Object
类的定义内执行include Foo
相同.这样做的用途是,Foo
的所有实例方法现在都随处可用.
Outside of any class definition include Foo
will add Foo
to the ancestors of Object
. I.e. it is the same as if you did include Foo
inside the definition of the Object
class. The use doing this is that all of Foo
's instance methods are now available everywhere.
这篇关于在Ruby或Rails中,为什么要“包含"?有时在课堂上,有时在课堂外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!