# Iterate over one record at a time using ActiveRecord, instead of being slurpy.


def self.foreach(conditions = nil, &block)
conn = connection.raw_connection

sql = "select * from #{table_name}"
sql += " where #{conditions}" if conditions

begin
raw_cursor = conn.exec(sql)

while rec = raw_cursor.fetch_hash
object = self.new

# To get around protected attributes we must assign all attributes
# individually, instead of passing a single hash to self.new.
rec.each{ |key, value|
cname = key.downcase
object.send("#{cname}=", value)
}

yield object
end
ensure
raw_cursor.close if raw_cursor
end
end

Read more: http://feeds.dzone.com/~r/dzone/snippets/~3/QyD6ZAtVq5w/12559