Ruby's construction process is flexible: it allows you to short-circuit the object construction process itself, allowing you to provide your own instance of the object being construction.
An example is in order:
https://gist.github.com/jtigger/6595108
This feature is handy, for example, when backing object instances with a cache. In this case, when a client programmer "constructs" an object the first time, you'll want to build it, as usual and return that instance (see the call to super in the gist). However, if they request the same object a little later, and it's still in the cache, you'd rather skip creating the object and just return the instance that's in the cache.
Unpacking that construction flow a little deeper...
- first call to Foo.new(1) results in a "cache miss" and therefore the new() method of the super-class of Foo (i.e. Object.new()) is invoked by calling super.
- the second call of Foo.new(1), finds the instance of Foo created during the first invokation. This is a "cache hit" and merely returns that instance from the cache.
Pretty cool!
Thanks to Jörg W Mittag on StackOverflow for this idiom.
p.s. also note that super not only calls the same method on the super-class, but automatically passes the same parameter list that was sent to the current method. In the example in the gist, id is passed to Object.new().
No comments:
Post a Comment