Class#allocate and its uses
memory-management, ruby
Solution
The main reason `allocate` exists is to allow you to build custom constructors for your objects. As the article you linked mentioned, you can envision the `SomeClass.new` method as doing something like the following by default:
class SomeClass
def self.new(*a, &b)
obj = allocate
# initialize is a private instance method by default!
obj.send(:initialize, *a, &b)
end
end
Despite what the documentation says, the existence of the `allocate` method is not so much about memory management as it is about providing some finer grained control over the object creation lifecycle. Most of the time, you won't need this feature, but it is useful for certain edge cases.
For example, in the Newman mail framework, I used this technique to implement a fake constructor for a TestMailer object; it implemented the `new` method for API compatibility, but actually returned a single instance regardless of how many times it was called:
class Newman::TestMailer
def self.new(settings)
return self.instance if instance
# do some Mail gem configuration stuff here
self.instance = allocate
end
attr_accessor :instance
end
I've not seen many other use cases apart from redefining `new` as shown above (although I imagine that some weird serialization stuff also uses this feature). But with that in mind, it's worth pointing out that Ruby consistently provides these kinds of extension points, regardless of whether or not you'll need to use them regularly. Robert Klemme has a great article called The Complete Class which I strongly recommend reading if you want to see just how far this design concept has been taken in Ruby :-)
Problem
After having read http://www.seejohncode.com/2012/03/16/ruby-class-allocate/ and looking more into the allocate method: http://www.ruby-doc.org/core-1.9.3/Class.html#method-i-allocate I became very curious. Ruby was built in a way that we did not have to manually allocate or free space for/with objects, but we are given the ability to do so. Why? What are the uses in Ruby of allocating Objects manually? The article I read showed a custom initialize method, but are the uses of it so limited?