Rubernate

{Dynamic Persistence
for Dynamic Language}

#
# This example demonstrates polymorphism of persistent objects
#   
require 'ex0_config'

# Base class for Shapes
class Shape
  persistent # make it persistent

  # Draws shape
  # This method must be overriden by subclasses
  def draw
    raise "Not implemented... "
  end
end

# Represents Sphere
class Sphere < Shape
  persistent :x, :y, :radius

  def initialize x, y, radius
    self.x = x # Note: we sould use self.x method! not field @x
    self.y = y
    self.radius = radius
  end

  def draw
    "Sphere [#{x}, #{y}], radius: #{radius}"
  end
end

# Represents Rectangle
class Rectangle < Shape
  persistent :x0, :y0, :x1, :y1

  def initialize x0, y0, x1, y1
    self.x0, self.y0 = x0, y0
    self.x1, self.y1 = x1, y1
  end

  def draw
    "Rectangle [#{x0}, #{y0}], [#{x1}, #{y1}]"
  end
end


# Represents Composistion of objects
class Composition < Shape
  persistent :shapes

  def initialize shapes = []
    self.shapes = shapes
  end

  def draw
    "Composistion of: " + shapes.map{|s| "[#{s.draw}]"}.join(', ')
  end
end

Rubernate.session do
  # Create sphere
  s = Sphere.new(1.0, 2.0, 3.45).attach

  # Create rectangle
  r = Rectangle.new(1, 2, 5, 6).attach
end # Commit transaction


c_pk = nil
Rubernate.session do
  # Find all Shapes - objects with classes derived from Shape (using derived method).
  shapes = Rubernate.find_by_query 'Select :s; Where s.derived(Shape)'
  
  # Draw each shape
  for s in shapes
    puts s.draw
  end
  
  # Create composition of shapes
  comp = Composition.new(shapes).attach
  # Remember pk of composistion
  c_pk = comp.primary_key  
end # Commit transaction

Rubernate.session do
  # Find composition
  comp = Rubernate.find_by_pk c_pk
  
  # Draw composition
  puts comp.draw  
  
  # Remove all shapes
  comp.shapes.each{|s| s.remove!}
  # Remove composititon
  comp.remove!  
end