About a year ago, I wrote a simple type enforcement library that adds a
should_be method to the Object class. This method looks like this:
def should_be(types, varName)
# types is either a Class or an array of Classes
# that are legal types (or super-types, if you will)
# for self
# varName is the symbol for the variable; we use this
# when we throw the exception
<type checking code>
# we throw an exception if self is not of one of
# the types specified
end
So, say we have a method print_line that takes two parameters (1) an
integer line number and (2) a string which is the line.
def print_line(lineNo, line)
lineNo.should_be(Integer, :lineNo)
line.should_be(String, :line)
# by now, we would have thrown a TypeError if lineNo
# and line are not an Integer and a String respectively
<code to make this method live up to its name>
end
We’ve been using this for a year now. Several months ago I rewrote it
so that it is in C so that it doesn’t appreciably increase overhead.
The good news is that it works quite well and completely fulfills our
type checking needs.
The issue is that I don’t like having to pass the symbol for the
variable, because it strikes me as inelegant. Right now, I only pass
the symbol so that I can construct an error message saying (for
example) “variable ‘loginIDs’ is of the wrong type ‘Integer’; expected
’Array’”. I feel that it would be much cleaner to simply say
loginIDs.should_be(Integer). I may be quite dense and perhaps I am
missing something obvious, but I have combed through the source code
for 1.6.x and 1.8.1 and I haven’t been able to find anything (I’ve
tried every conceivable combination of ‘object id’ and 'name for id’
functions, but of course these are two entirely different kinds of
ids).
Thus my question:
Is there any way to access the name of a given variable instance from
within it? In other words, for any object x, is there C function to
which I can pass self to determine that the program calls it ‘x’?
Thanks,
Dave
···
David King Landrith
(w) 617.227.4469x213
(h) 617.696.7133
Life is tough. It’s even tougher if you’re
an idiot. --John Wayne
public key available upon request