← Back to Upcase

Questions about Dependency Injection and Rails


(Kurt Mueller) #1

Hey guys,

Recent subscriber to Thoughtbot Upcase. There have been a lot of great videos about Inversion of Control / Dependency Injection / Dependency Inversion and why loosely coupling classes together can lead to better code.

However, I am wondering (and maybe it’s explained in a video I missed) where and how the actual wiring together of different parts takes place. Where this should occur in the context of a Rails application?

Thanks for any help. Let me know if you don’t know what I’m talking about.


(Pedro Moreira) #2

@KurtMueller As with most things… it depends :slight_smile:

How far up the stack are you happy pushing things? Personally, I rarely go past the controller level. If you want to keep pushing, try having your wiring in a initializer, for instance. Or keep going up, into Middleware.

Have a look at the Payload gem by thoughtbot and the way it is used for Upcase exercises app, specifically the config/dependencies file.

If you don’t mind me offering some advice, I’d start by inverting control up to the controller layer.

Let the controllers be the place that have knowledge of class names and how to instantiate each one with the correct dependencies. Then you can have a better perspective for the need to keep pushing up.

Maybe some of the wiring is needed in more than one place. Move it up the stack so it is available. Eventually, you’ll have the feel for applying/organising DI in a Rails app.

I’ve seen projects that have a single wiring file and are long lasting apps. That file tends to be huge and rather difficult to manage. Of course, the same can start to happen to your controllers.

It is always, always, a matter of thinking through the trade offs between your decisions.

Hope this helps :slight_smile:


(Kurt Mueller) #3

Thanks for the reply @pedromoreira.

In one of thoughtbot’s blog posts concerning Sandi Metz’ 5 rules, the author stated that they started using the Facade pattern in their controllers to ensure that no more than one instance variable is instantiated in a controller action. I’m assuming no more than one instance variable set in a controller action means no before/after action callbacks as well.

Also, the link you posted to the payload gem is broken and is not a repo the Thoughtbot organization page :frowning: .


(Pedro Moreira) #4

No problem, glad to help.

I guess access to the Payload repo might depend on your Upcase subscription. I’m not quite sure on what you mean regarding instance variables, maybe you can clarify on that?