Friday, December 9, 2011

Serialize and deserialize object in ruby

Hello Rubies,
          Want to serialize and deserialize the ruby object? than use the inbuilt method of ruby.

Assume have the field says 'content' as text field of xyz table and it stores the value in serialize hash format but when we do the sql query to retrieve content than it gives output as normal string format.

content has value:
---
ruby:
  :value: 50
  :label: "ruby %"
java:
  :value: 30
  :label: "java %"
c:
  :value: 50
  :label: "c %"

Lets trying to get the content value by raw sql statement like "select content from xyz" than it return text (string) object.

now we load the object in serialize form by
puts YAML::load(content)
visa versa we have string and set to serialize object than need to use  
puts YAML::dump(content)
Same way around if you have deserialize content and want the serialize form then use content.to_yaml. It gives result in serialized form.

No comments:

Post a Comment