在Ruby或Rails中,为什么要“包含"?有时在课堂上,有时在课堂外? [英] In Ruby or Rails, why is "include" sometimes inside the class and sometimes outside the class?

查看:68
本文介绍了在Ruby或Rails中,为什么要“包含"?有时在课堂上,有时在课堂外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以为

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 FooFoo添加到该类的祖先,从而使所有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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆