4 ms·
I use a factory for the same things you use them for: to build objects. For example, I use factories to create test objects that are complicated to set up (usi
by r00k 14y ago
I use a factory for the same things you use them for: to build objects.
For example, I use factories to create test objects that are complicated to set up (using a gem named factory_girl, actually).
Also, in Ruby, every class is a factory for its own instances. If I define a class called User, I can assign the class object User to a variable:
factory = User
Then I can call
factory.new
and receive a new User instance.
As for DI, it's not wrong, nor is it unidiomatic. Plenty of folks in the community use it, and often.
A commenter elsewhere in this thread says that DI is unnecessary in Ruby because you can just reopen or redefine a class whenever you want. That's technically true, but isn't a good practice, as it can lead to some rather rapid foot shootery.
If you want to swap in different-behaving dependencies, DI is a straightforward choice. Reopening an existing class and mangling it can cause very confusing behavior, and is generally avoided by experienced Rubyists.
- tptacek 14y agoI thought you perhaps meant something more than class objects. Regarding DI: Jamis Buck infamously used DI for net/ssh and posted that he regretted doing so, because DI felt out of place in Ruby. I'm not spoiling for an argument about its virtues. Regarding "experienced Rubyists" and reopening classes, I think you should have a look at activesupport/core_ext.