ruby picture

RCR 263: Metaclass initialize method

Submitted by Zallus (Sun Jul 04 23:07:04 UTC 2004)

Abstract

A simple method for declaring code that will be executed in both the current module/class, and inherited/extended modules/classes' scopes.

Problem

There is no simple way to have code execute in both a class scope, and in all subclass scopes. Say, for example that you have a class where you want to initialize class-instance-variables to certain values, but that can be overridden. The current-scope code can just be inlined, and the subclass-scope code can be declared as:
def self.inherited(sub)
  sub.class_eval do<br>
    # code<br>
  end<br>
end
But these cannot be converged without redundancy.

Proposal

I suggest, though the name may change slightly on implementation, a class-method named initialize. This would be called, if defined, by the Class.new method, akin to Class#new calling the created instances' #initialize method. It would necessitate having no parameters, unless some additional syntax could be introduced in the form of ClassConstant(*args). Then, super() would be used to initialize the parent class, as in the initialize instance-method.

Analysis

I don't really believe this would impact Ruby in many ways, and could easily be completely ignored by people who don't use it. However, for initializing class instance variables, registering with class factories, etc., it provides a nice template.
The code would have to also be run once a self.initialize method had first been declared in the root (non-subclass) class (you could, of course, just call it in-line, but that's kludgey). Such method would also have to be called every time it were redefined.

Implementation

Can't see this possibly being able to implement in ruby-code, but here's a slightly more crippled idea (probably doesn't function):
  def Class.new(*args)<br>
    classInst = super(*args)<br>
    classInst.class_eval { initialize() if method_defined?(:initialize) }<br>
    classInst<br>
  end
ruby picture
Comments Current voting
Strongly opposed 0
Opposed 0
Neutral 0
In favor 0
Strongly advocate 0
ruby picture
If you have registered at RCRchive, you may now sign in below. If you have not registered, you may sign up for a username and password. Registering enables you to submit new RCRs, and vote and leave comments on existing RCRs.
Your username:
Your password:

ruby picture

Powered by .