14

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
  • include Bar like this is a pernicious error - it'll change ApplicationController the way you want it to, but also change every other object in the application. Commented Jan 19, 2016 at 1:01

1 Answer 1

21

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.