Forum: Ruby with YAML can I retrieve the class type back???

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Greg H. (Guest)
on 2009-03-05 09:15
(Received via mailing list)
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
David M. (Guest)
on 2009-03-05 09:41
(Received via mailing list)
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.
Greg H. (Guest)
on 2009-03-05 11:29
(Received via mailing list)
2009/3/5 David M. <removed_email_address@domain.invalid>

> 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
This topic is locked and can not be replied to.