Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Serializing objects in Ruby

Source: Object Serialization: Ruby Study Notes - Best Ruby Guide, Ruby Tutorial [rubylearning.com]
<snip>
Java features the ability to serialize objects, letting you store them somewhere and reconstitute them when needed. Ruby calls this kind of serialization marshaling.

We will write a basic class p051gamecharacters.rb just for testing marshalling.
   1  
   2  # p051gamecharacters.rb  
   3  class GameCharacter  
   4   def initialize(power, type, weapons)  
   5     @power = power  
   6     @type = type  
   7     @weapons = weapons  
   8   end  
   9   attr_reader :power, :type, :weapons  
  10  end  


The program p052dumpgc.rb creates an object of the above class and then uses Marshal.dump to save a serialized version of it to the disk.

   1  
   2  # p052dumpgc.rb  
   3  require 'p051gamecharacters.rb'  
   4  gc = GameCharacter.new(120, 'Magician', ['spells', 'invisibility'])  
   5  puts gc.power.to_s + ' ' + gc.type + ' '  
   6  gc.weapons.each do |w|  
   7   puts w + ' '  
   8  end  
   9   
  10  File.open('game', 'w+') do |f|  
  11   Marshal.dump(gc, f)  
  12  end 


The program p053loadgc.rb uses Marshal.load to read it in.

   1  
   2  # p053loadgc.rb  
   3  require 'p051gamecharacters.rb'  
   4  File.open('game') do |f|  
   5   @gc = Marshal.load(f)  
   6  end  
   7   
   8  puts @gc.power.to_s + ' ' + @gc.type + ' '  
   9  @gc.weapons.each do |w|  
  10   puts w + ' '  
  11  end  


Marshal only serializes data structures. It can't serialize Ruby code (like Proc objects), or resources allocated by other processes (like file handles or database connections). Marshal just gives you an error when you try to serialize a file.

</snip>

Marshalize (Cache) ActiveRecord Query Results

A quick way to cache results in a file and read from the file on subsequent requests instead of the database. Makes the initial query a bit slower, but later queries *much* faster.

   1  
   2  class MyCachedModel < ActiveRecord::Base
   3    class << self
   4      alias_method :rails_original_find_by_sql, :find_by_sql
   5      def find_by_sql(sql)
   6        cache_filename = Base64.encode64(sql)
   7        if File.exists? cache_filename
   8          Marshal.load(File.open(cache_filename))
   9        else
  10          Marshal.dump(records = rails_original_find_by_sql(sql), File.open(cache_filename, 'w'))
  11          return records
  12        end
  13      end
  14    end
  15  end
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS