Instead of MySql, use ActiveRecord or other ORM

While it’s trivial to connect to the db with ActiveRecord:

This call creates a connection to our database.

ActiveRecord::Base.establish_connection(
:adapter => “mysql”,
:host => “127.0.0.1”,
:username => “ruby”,
:password => “password”,
:database => “rss2mysql”)
class Items < ActiveRecord::Base
end

It’s unclear to me how to get an array/queue/whatever of each of the
Item
instances in the db into memory. Do you first create an array, and then
how do you populate it? I’m not tied to ActiveRecord, that’s just what
I’ve been using so far. My code:

[email protected]:~/rb$
[email protected]:~/rb$ cat mysql.rb
#!/usr/bin/ruby

require ‘rubygems’
require ‘active_record’ #well, would like to use it
require ‘mysql’ #want to drop this
require ‘net/http’

$maxwidth = 12 # MAXIMUM WIDTH OF FIELD DISPLAYS

INITIALIZE AND CONNECT TO DATABASE test

mysql = Mysql.init()
mysql.connect(‘localhost’, ‘ruby’, ‘password’)
mysql.select_db(‘rss2mysql’)

PRINT OUT FIELD NAMES AND VALUES

puts
results = mysql.query(“describe rss2mysql.items;”)
results.each do |row|
column = row[0]
print column
($maxwidth - column.length).times {print " "}
end
puts
puts

urls = Queue.new

results = mysql.query(“SELECT url from rss2mysql.items;”)
results.each do |row|
row.each do |column|
print column
($maxwidth - column.length).times {print " "}
urls.push(Net::HTTP.new(column, 80)) #wrong loop
end
puts
end

SHUT DOWN THE DATABASE CONNECTION

mysql.close()

#####surely there’s a better way to iterate
#####need to process the queue of url’s

x = urls.length

x.times do
html = urls.pop
puts html
end

[email protected]:~/rb$

Basically, how to I make the above more db independant with some form of
ORM?

thanks,

Thufir

On Sun, 20 Sep 2009 18:14:07 +0900, Thufir wrote:
[…]

Basically, how to I make the above more db independant with some form of
ORM?

Well, I looked forever and only found the answer after posting:

[email protected]:~/rb$
[email protected]:~/rb$ cat iterate.rb
require ‘rubygems’
require ‘active_record’
require ‘feed_tools’

ActiveRecord::Base.establish_connection(
:adapter => “mysql”,
:host => “127.0.0.1”,
:username => “ruby”,
:password => “password”,
:database => “rss2mysql”)
class Items < ActiveRecord::Base
end

claims = Items.find( :all)

claims.each do |claim|
puts claims.object_id
end
[email protected]:~/rb$

thanks to:

http://www.rubyinside.com/advent2006/17-extendingar.html

-Thufir