You could do:

class Person
  FIELDS = :person_id, :last_name, :first_name, :home_phone,
:work_phone, :address, :city, :state, :zip
  attr_accessor *FIELDS
  def initialize(row=nil)
    FIELDS.each { |f| instance_variable_set("@#{f}",
row.by_field(f.to_s)) } if row == DBI::Row
  end
end

(though I'd advise against using the row == DBI::ROW - use
row.respond_to?(:by_field) instead, otherwise you'll probably have fun
when it comes time to unit tests...).

or if you want to make it a general case:

class DatabaseObject
  def self.db_field(*args)
    attr_accessor(*args)
    (@__db_fields||[]).concat(args)
  end
  def self.db_fields
    (@__db_fields||[]) + superclass.db_fields if
superclass.respond_to?(:db_fields)
  end 
  def initialize(row=nil)
    self.class.db_fields.each { |f| instance_variable_set("@#{f}",
row.by_field(f.to_s)) } if row.respond_to?(:by_field)
  end
end

class Person < DatabaseObject
  db_field :person_id, :last_name, :first_name, :home_phone,
:work_phone, :address, :city, :state, :zip
end

Which is pretty much what you'll get from any of the ORM libraries,
though they'll usually get the list of fields by querying the database,
so you don't even have to do that in your code.

(all code is untested - that's your job).

> -----Original Message-----
> From: Sam Kong [mailto:sam.s.kong / gmail.com] 
> Sent: Wednesday, 2 November 2005 1:17 PM
> To: ruby-talk ML
> Subject: How can I avoid this boring code?
> 
> Hi!
> 
> I'm creating a class.
> I wonder if there's a better way.
> 
> require 'dbi'
> 
> class Person
>   attr_accessor :person_id,
>     :last_name,
>     :first_name,
>     :home_phone,
>     :work_phone,
>     :address,
>     :city,
>     :state,
>     :zip
> 
>   def initialize(row=nil)
>     if row.class == DBI::Row then
>       @person_id = row.by_field("person_id")
>       @last_name = row.by_field("last_name")
>       @first_name = row.by_field("first_name")
>       @home_phone = row.by_field("home_phone")
>       @work_phone = row.by_field("work_phone")
>       @address = row.by_field("address")
>       @city = row.by_field("city")
>       @state = row.by_field("state")
>       @zip = row.by_field("zip")
>     end
>   end
> end
> 
> The code in initialize method is very boring.
> How could I make it simpler?
> 
> Thanks in advance.
> 
> Sam
> 
> 
> 
> 
#####################################################################################
This email has been scanned by MailMarshal, an email content filter.
#####################################################################################