File: emailtable.rb

Project: Invitation to Ruby

#!/usr/bin/env ruby

require 'dbi'

class Person
  def initialize(first, last, nick, email, kind)
    @first = first
    @last = last
    @nick = nick
    @email = email
    @kind = kind
  end

  def show
    printf "%-15s %-12s %s\n",
      "#{@first} #{@last}", "#{@nick}/#{@kind}", @email
  end
end

def Person.from_hash(hash)
  params = [
    'first', 'last', 'nick', 'email', 'type'
  ].collect { |n| hash[n] }
  self.new(*params)
end

db = DBI.connect ("DBI:Pg:jim", "jim")

sql = <<-SQL
SELECT first, last, nick, email, type
FROM person, email
WHERE person.personid = email.personid
ORDER BY nick, type
SQL

people = Array.new
db.select_all(sql) { |row|
  people << Person.from_hash(row)
}

db.disconnect

people.each { |who| who.show }


[ Index ][ Table of Contents ]
Generated by [ source2html ]