views:

494

answers:

3

I am developing an app that needs to send text messages, so I have carrier information stored in a database. I also need that information in an XML file for client side code to read. To make this happen, I am writing a script that reads the carrier information from the DB and creates an XML file in the config directory. I felt this script would fit best in lib/tasks.

I need to access the database from this script, but I want to use some object to access it. If I use

db = Mysql.new("domain", "username", "password", "database")

I will have to keep multiple versions for different environments because I do not use MySQL all the time. That would be very sloppy. I am sure there is a way to do this. I tried to just access the object...this is what I have so far:

RAILS_HOME = File.expand_path(File.join(File.dirname(__FILE__),"../.."))
RAILS_CONFIG = "#{RAILS_HOME}/config"

f = File.new("#{RAILS_CONFIG}/mls_widget_config.xml", "w")
carriers = Carrier.find_all
f.write carriers
f.close

But Carrier is not defined, which makes sense. How can I give this script access to the the Carrier object in the DB?

Also as a side, if anyone knows how to easily convert what I read from the DB into proper XML that would be great. I was going to write something custom real quick.

Thank you!

+2  A: 

You're actually almost there; I'd just recommend requiring your Rails environment as part of the script, like so:

RAILS_HOME = File.expand_path(File.join(File.dirname(__FILE__),"../.."))
RAILS_CONFIG = "#{RAILS_HOME}/config"
require "#{RAILS_CONFIG}/environment"

Now you should have access to all of your domain structure. Rails also includes default XML serialization through the use of the to_xml method call; try Carrier.find(:all).to_xml.

Brian Guthrie
+2  A: 

By convention, lib/tasks is usually reserved for rake tasks - you might want to put your library code in its own directory. lib/messaging, maybe?

Are you running an old version of Rails? find_all doesn't work in recent versions: 'find(:all)' or just 'all' are the methods nowadays.

File.new("#{RAILS_ROOT}/mls_widget_config.xml", "w") do |f|
  Carrier.all.each { |carrier| f.puts carrier.to_xml }
end
Mike Woodhouse
This doesn't explain how to link to the model class, as the question asks.
Tilendor
+7  A: 

You can enable a Rake task to access your models by defining your task like this:

task :my_task => :environment do
  # Task code
end

Note the => :environment, which grants this access. You can then instruct your Rake task to use different environments this way:

rake RAILS_ENV=development my_task
rake RAILS_ENV=production my_task

As for XML serialization, you can use the built-in to_xml method, such as:

Carrier.all.to_xml

Note that the method .all is a recent addition to Rails, and is an alias for .find(:all).

Ron DeVera