3 ms·
"class declarations are loaded as constants at run time" Let's say I create a class called User. When ruby sees that declaration, it creates a constant called
by dutchrapley 15y ago
"class declarations are loaded as constants at run time"
Let's say I create a class called User. When ruby sees that declaration, it creates a constant called User to contain that object. When I create a new instance:
user = User.new
"User" is a constant whose value is the object/class. "new" is a method that calls the constructor (if one exists) and creates a new instance. The same applies when you call something like:
User.find
You're not calling find() on an instance, you're calling it on the object that's loaded into the constant "User". The class declaration "class User" is saying User is the name of the class; User is also the constant in which it's stored. It's also what allows you to reopen a class on the fly to extend it with more methods.
"I think there's a third purpose to DI that you didn't mention. The container does instantiate an object and inject it ("wire it") into another object, but the real benefit is that you can externally configure which object to swap in."
True, but I've never found myself switching objects out on a regular basis.
As you mentioned, the conditional approach probably isn't the best. What I'm assuming now is that you're based on your deployment, you might use a different bean factory configuration file? And this works as long as UserLdap and UserDb implement the same interface?
That being said, instead of sprinkling conditionals throughout user, you can dynamically assign User initially.
User = UserDb
OR
User = UserLdap
and as long as UserDb or UserLdap had a find() method, you could then call
User.find
Remember, User is now a constant that references the same value as UserDb or UserLdap
Does that help clarify?
- geebee 15y agoResponding very late, sorry... It does help clarify this, thanks. It does still leave the problem that you have to specify the "type" in the code and can't swap it out. That said, I think this could probably be handled easily with a yaml file (just specify the class you want to instantiate every time a user is created)? I may try that some time.