require 'prb/prb'
require 'prb/opt'

class World
  class UserList < PRb::PRbRoot
    def add_user(name)
      transaction do
	raise 'already regsitered' if self[name]
	self[name] = User.knew(name)
      end
    end
  end

  class User < PRb::PRbRoot
    def init(nm)
      self.name = nm
    end
    prb_attr :name, :email
  end

  def transaction(&block)
    PRb.primary.transaction(&block)
  end

  def initialize
    root = PRb.primary.root
    root.transaction do
      world = root[$0]
      unless world
	world = UserList.knew
	$prb.root[$0] = world
      end
      @world = world
    end
  end

  def demo
    @world.add_user('seki') rescue RuntimeError

    he = transaction do
      he = @world['seki'] 
      p he
      p he.name
      p he.email
      he
    end
    
    he.email = 'seki@ruby-lang.org'
    p he.email
  end

  def add(name)
    @world.add_user(name) rescue RuntimeError
    p [name, @world[name]]
  end
end

def main
  pool = DBIPool.new(*DBIPool.check_options(ARGV))
  $prb = PRb::Store.new(pool)
  world = World.new
  world.demo
end

main
