With YAML can I retrieve the class type back?

Hi,
If I wanted to persist different Ruby types (e.g. float, BigDecimal,
integer, string) to a database based table (e.g. column names KEY and
VALUE), if I use the “to_yaml” method to serialize their values and
store
them as strings, what’s the easiest way to retrieve them back to a Ruby
variable such that they are of the original type (i.e. not a YAML type).

E.g. Want to be able to do things such as (assume I have a model called
Config):

Config.create!(:key => “interest_rate”, :value =>
BigDecimal(‘12.12’).to_yaml)
Config.create!(:key => “age”, :value => 12.to_yaml)

and then later

ir = Config.find_by_key('interest_rate") # and the variable should be
of
type BigDecimal
ir = Config.find_by_key('age") # and the variable should be of type
Integer
etc

Greg H. wrote:

Hi,
If I wanted to persist different Ruby types (e.g. float, BigDecimal,
integer, string) to a database based table (e.g. column names KEY and
VALUE), if I use the “to_yaml” method to serialize their values and store
them as strings, what’s the easiest way to retrieve them back to a Ruby
variable such that they are of the original type (i.e. not a YAML type).

If you’re using Rails, there’s a helper built in. For example, if your
column named “value” is the object you want stored that way:

class Whatever < ActiveRecord::Base
serialize :value

end

If you want to do it yourself, use YAML.load:

serialized = my_object.to_yaml
object = YAML.load(serialized)

I have no idea if this is safe for untrusted data – I suspect it’s not.
So, use this with your own databases, not with random web services, at
least without putting some thought into it.

2009/3/5 David M. [email protected]

If you’re using Rails, there’s a helper built in. For example, if your
column named “value” is the object you want stored that way:

class Whatever < ActiveRecord::Base
serialize :value

end

If you want to do it yourself, use YAML.load:

thanks David - I hadn’t realized this was there