Austin Ziegler wrote:
Object.const_set(name, klass)
Thanks all. Here's what I'm trying to do exactly:
ERROR_CODES = YAML::load open('config/errorcodes.yml').read
for k, v in ERROR_CODES
Object.const_set(k, Class.new(Exception) {
def to_s
"{code: #{v['code']}, message: #{v['message']}}"
end
})
end
o = MyException.new # "MyExcetion" is defined in the YAML file
puts o
Unfortunately, this doesn't seem to work:
test.rb:8:in `to_s': undefined local variable or method `v' for #<NotAFeed:0x2b6ca08> (NameError)
from test.rb:14:in `puts'
from test.rb:14
Here's the equivalent Python code (which works):
ERROR_CODES = syck.load(open('config/errorcodes.yml').read())
for k, v in ERROR_CODES.items():
nexc = new.classobj(k, (Exception,), {})
code, message = v
tostr = lambda self: "{code: %s, message: %s}" % code, message
setattr(nexc, "__str__", new.instancemethod(tostr, None, nexc))
globals()[k] = nexc
try:
raise MyException
except MyException, e:
print e # prints "{code: ..., message: ...}"
Thanks again.
--Jonas Galvez