Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class#allocate and its uses

Tags:

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?

like image 969
Robert 'Jet' Rowe Avatar asked Oct 24 '12 23:10

Robert 'Jet' Rowe


People also ask

What do you mean by class in school?

1 : a group of students who are taught together regularly I'm the youngest in my class. 2 : one of the meetings of students being taught I'm late for class. 3 : a course of instruction a class in science. 4 : a group of students who graduate together the senior class.

Is class owned by Zoom?

Zoom, the popular video conferencing tool, has been adapted by a startup -- ClassEDU -- founded by education technology veterans including the Blackboard co-founder and former CEO.


1 Answers

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 :-)

like image 140
Gregory Brown Avatar answered Nov 13 '22 06:11

Gregory Brown