instead of MySql, use ActiveRecord or other ORM

T

Thufir

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:


thufir@ARRAKIS:~/rb$
thufir@ARRAKIS:~/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

thufir@ARRAKIS:~/rb$



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


thanks,

Thufir
 
T

Thufir

]
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:


thufir@ARRAKIS:~/rb$
thufir@ARRAKIS:~/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
thufir@ARRAKIS:~/rb$


thanks to:

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




-Thufir
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,968
Messages
2,570,150
Members
46,697
Latest member
AugustNabo

Latest Threads

Top