Showing posts with label YAML. Show all posts
Showing posts with label YAML. Show all posts

Thursday, July 5, 2012

Convert string to serialize hash

Hello Rubies,
        Do you phase the problem ? - sometime  when we are retrieving the serialized hash field from table we might get string as response. So in that case you can use one of the below solutions.

Eg. 

Model - User.rb
class User < ActiveRecord::Base
   serialize :content, Hash
end

convert string to serialize hash format by 

# get the one of the record from users table
user = User.first

either using
    user.content.to_yaml
or
    YAML.parse(user.content)
or
    YAML.load(user.content)

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.