Home > ruby > Serializing Objects in Ruby

Serializing Objects in Ruby

Simple object serialization in ruby can be done using two core ruby modules Marshal and Base64. Here is how its done

Marshalizer.rb


class Marshalizer
  def self.dump(obj)
    return Base64.encode64(Marshal.dump(obj))
  end

  def self.load(str)
    return Marshal.load(Base64.decode64(str))
  end
end

Sample Usage


class SampleObj
  attr_accessor :title, :description
end

class MarshalizerTest < Test::Unit::TestCase
  def test_serialization
    article = SampleObj.new
    article.description = "Test name"
    article.title = "Test title with 's"
    serialzied_article = Marshalizer.dump(article)
    assert_not_nil serialzied_article, "serialized article should not be nil"
    puts serialzied_article
    new_article = Marshalizer.load(serialzied_article)
    assert new_article
    puts new_article.inspect
    assert_not_nil new_article, "loaded article should not be nil"
    assert_instance_of SampleObj, new_article, "new_article should be of type article"
    assert_equal(article.title, new_article.title)
  end
end

ruby

  1. No comments yet.
  1. No trackbacks yet.