In Ruby or Rails, why is “include” sometimes inside the class and sometimes outside the class?

感情迁移 提交于 2019-12-21 07:29:06

问题


I thought

class ApplicationController < ActionController::Base
  include Foo

is to add a "mixin" -- so that all methods in the Foo module are treated as methods of the ApplicationController.

But now I see code that is

include Bar

class ApplicationController < ActionController::Base
  include Foo

So why is it outside of ApplicationController? How is that different from the more common use of putting it inside of ApplicationController?


回答1:


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.

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.



来源:https://stackoverflow.com/questions/5161428/in-ruby-or-rails-why-is-include-sometimes-inside-the-class-and-sometimes-outs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!