[LRUG] Understanding Ruby Tempfile documentation

Graham Ashton graham at effectif.com
Tue Jan 26 05:10:01 PST 2016


On Tue, 26 Jan 2016, at 12:39 PM, Jonathon Horsman wrote:
> 
> So what's the advantage of this instead of directly subclassing File?

I’ve never used it, but I’d say it comes down to taste, and a (potentially useful) implementation detail (i.e. context would help you decide whether there was a benefit to using it).

The implementation detail is highlighted in the original version of the Pickaxe book (interestingly, I can’t find the same text in more recent versions).

Have a look at the code snippet here where they define `Fred` as a subclass of `DelegateClass(Flintstone)`:

http://ruby-doc.com/docs/ProgrammingRuby/html/lib_patterns.html

"This is subtly different from using subclassing. With subclassing, there is only one object, which has the methods and the defined class, its parent, and their ancestors. With delegation there are two objects, linked so that calls to one may be delegated to the other.”

In other words, you can define methods on an instance of `Fred` in terms of a separate instance of `Flintstone`, instead of just calling inherited methods on your instance of `Fred`.

I can imagine circumstances where that would make life simpler, but if I've encountered one in real life, I’ve never noticed.



More information about the Chat mailing list