Rubernate

{Dynamic Persistence
for Dynamic Language}

require 'ex0_config'


class P
  persistent :prop

  def initialize prop = nil
    self.prop = prop
  end

  # Calculates sum of values in collection.
  # prop.inject(0) {|sum, o| sum + o.prop}
  def sum
    sum = 0
    for o in prop
      sum += o.prop
    end
    sum
  end
end


pk = nil
# Create test data
Rubernate.session do
  o  = P.new.attach
  pk = o.primary_key

  o.prop = []

  # Create 1000 new objects and put them into array.
  for i in 1..500
    o.prop << P.new(i).attach
  end
end

require 'benchmark'

Rubernate.session do
  o = Rubernate.find_by_pk pk   # Load object
  puts "o.prop.size = #{o.prop.size}"
  puts Benchmark.measure { puts "o.sum = #{o.sum}"}
end


puts "\nThe same but with object pre-loading..."
Rubernate.session do
  o = Rubernate.find_by_pk pk  # Load object
  puts "o.prop.size = #{o.prop.size}"

  puts Benchmark.measure {
    # Pre-load objects
    Rubernate.find_by_query "select ref_value from
                             r_params where object_pk = ?", [pk]
    puts "o.sum = #{o.sum}"
  }
end


puts "\nTurn on automaic object pre-loading..."
Rubernate.settings[:lazy_load] = :collection
Rubernate.session do |rt|
  o = Rubernate.find_by_pk pk  # Load object
  puts "o.prop.size = #{o.prop.size}"
  puts Benchmark.measure {puts "o.sum = #{o.sum}"}
end