开发者

Ruby on Rails Dependency Injection

开发者 https://www.devze.com 2023-04-12 21:25 出处:网络
By day I am a .NET ASP.NET MVC developer but by night I\'m working on an e-commerce application built in RoR 3.1.

By day I am a .NET ASP.NET MVC developer but by night I'm working on an e-commerce application built in RoR 3.1.

We are starting with one payment processor with the understanding that we'll be 开发者_如何学编程moving to another one in 6 to 8 months. I don't want to repeat code so if I were doing this in .NET, I'd create an interface and create a class to implement that interface. I'd create two classes for each payment processor and then just use dependency injection to specify which one to use like:

ninjectKernel.Bind<IPaymentProcessor>().To<PaymentProcessor1>();

and then when we switch all I'd have to do is change that one line to PaymentProcessor2.

Are there any tutorials you know about or code samples out there that would lead me down the same path for ruby on rails? I know ruby is dynamic and I won't need an interface.

Any guidance would be greatly appreciated.

Thanks!


Dependency injection is usually unnecessary with Ruby. Jamis Buck blogged extensively about the reasons why. Well worth a read.


Take advantage of duck typing, which is part of the dynamic nature of Ruby. If both of your payment processor classes respond appropriately to the same methods that are used in your app, then you can interchange them freely. No DI framework necessary.


The general consensus is that while the DI pattern is relevant in Ruby, a DI container is not necessary.

Jamis Buck was underway with a DI framework called Needle, but later changed tack and stated that, while he uses the DI pattern every day, a container is simply not necessary, because "Ruby is plah-doh, while the Java, .NET and other languages that require a library to manage DI concerns are blocks".

This idea is very commonly misinterpreted that "you don't need DI in Ruby". Jamis' message was that a container is not necessary, just as its not strictly necessary in any language - but even more so in Ruby.

While the consensus is that a container is unnecessary there are quite a few out there. One notable is that of Jim Weirrich, the author of Rake and rspec. He created one called Dim, which stands for DI-minimal.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号