Archive

Posts Tagged ‘ruby’

Serializing Objects in Ruby

May 24th, 2008

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

Ruby Mobile Browser Detector (port of JMBD)

May 24th, 2008

I have successfully ported Java Mobile Browser Detector to ruby. I am sure there are other existing utilities to achieve this but I found this to more simpler to understand and use. It works well with my mobile site Fundu.mobi developed on rails. I though it would be useful for someone so here is the code rmbd.zip.

Here is how you can use it in any controller


class SampleController < ApplicationController
    def index
      device_config = DeviceConfigDetector.detect_capabilities_for_request(request);
      logger.debug("device config = #{device_config.inspect}")
    end
end

ruby ,