YAML and Class

M

Martin Hart

Hi all,

I notice that the default YAML (ruby 1.8.1) does not dump or load Class by
default.
I have extended my local copy to do so, but now I wonder if there is a reason
why it does not support this feature that I have overlooked/not fully
appreciated?

Cheers,
Martin

FYI - this is my patch (Is there another way of creating a class without
having to eval the string?)

YAML.add_ruby_type(/^class/) { |type, val|
val =~ /\A[A-Z][A-Za-z0-9_]*:):[A-Z][A-Za-z0-9_]*)*\z/ or raise YAML::Error,
"Invalid Class: #{val.inspect}"
eval val
}

class Class
def to_yaml(opts = {})
YAML::quick_emit(nil, opts) { |out|
out << "!ruby/class "
self.name.to_yaml:)Emitter => out)
}
end
def is_complex_yaml?
false
end
end
 
W

why the lucky stiff

Martin said:
Hi all,

I notice that the default YAML (ruby 1.8.1) does not dump or load Class by
default.
nor does marshal:
TypeError: can't dump anonymous class #<Class:0x81d2d14>
from (irb):1:in `dump'
from (irb):1

i can't recall why this is, but the rule is there because I've adhered
to marshal's rules. nahi or matz is better equipped to answer. i
thought we had this discussion on ruby-core, but i can't seem to find
the reasoning.

_why
 
Y

Yukihiro Matsumoto

Hi,

In message "Re: YAML and Class"

|nor does marshal:
|
| >> Marshal.dump( Class.new )
| TypeError: can't dump anonymous class #<Class:0x81d2d14>
| from (irb):1:in `dump'
| from (irb):1
|
|i can't recall why this is, but the rule is there because I've adhered
|to marshal's rules. nahi or matz is better equipped to answer.

Just because anonymous class cannot be passed to another process.

matz.
 
M

Martin Hart

Hi,
|i can't recall why this is, but the rule is there because I've adhered
|to marshal's rules. nahi or matz is better equipped to answer.

Just because anonymous class cannot be passed to another process.

matz.

OK, thanks.

I'll continue to use the tweak in my programs as I can ensure that receiving
process already has the class defined :)


Cheers,
Martin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,153
Members
46,699
Latest member
AnneRosen

Latest Threads

Top