Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 921
nonopolarity Avatar asked Mar 01 '11 22:03

nonopolarity


People also ask

What is the difference between include and extend in Ruby?

In simple words, the difference between include and extend is that 'include' is for adding methods only to an instance of a class and 'extend' is for adding methods to the class but not to its instance.

Can we include class in Ruby?

Ruby allows you to create a class tied to a particular object. In the following example, we create two String objects. We then associate an anonymous class with one of them, overriding one of the methods in the object's base class and adding a new method.

What is the difference between a class and a module Ruby?

What is the difference between a class and a module? Modules are collections of methods and constants. They cannot generate instances. Classes may generate instances (objects), and have per-instance state (instance variables).


1 Answers

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.

like image 197
sepp2k Avatar answered Oct 23 '22 13:10

sepp2k