I'm developing an application that must send texts, and so i have company information saved inside a database. I additionally need that information within an XML apply for client side code to see. To achieve this, I'm writing a script that reads the company information in the DB and produces an XML file within the config directory. I felt this script would fit very best in lib/tasks.

I have to access the database out of this script, but I wish to apply certain resist can get on. Basically use

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

I will need to keep multiple versions for various conditions because I don't use MySQL constantly. That might be very sloppy. I am certain there's a method to do that. I attempted to simply access the item...this is exactly what I've to date:

RAILS_HOME = File.expand_path(File.join(File.dirname(__FILE__),"../.."))

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

But Company isn't defined, making sense. How do i give this script accessibility the Company object within the DB?

Also like a side, if anybody understands how to easily convert things i read in the DB into proper XML that might be great. I would write something custom here real quick.


You are able to enable a Rake task to gain access to your models by determining your career such as this:

task :my_task => :environment do
  # Task code

Note the => :environment, which grants or loans this access. After that you can instruct your Rake task to make use of different conditions by doing this:

rake RAILS_ENV=development my_task
rake RAILS_ENV=production my_task

For XML serialization, you should use the built-in to_xml method, for example:


Observe that the technique .all is really a recent accessory for Rails, and it is an alias for .find(:all).

You are really almost there I'd just recommend needing your Rails atmosphere included in the script, like so:

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

Now you ought to have use of all your domain structure. Rails includes default XML serialization by using the to_xml method call try Carrier.find(:all).to_xml.

By convention, lib/tasks is generally restricted to rake tasks - you might like to place your library code in the own directory. lib/texting, maybe?

Are you currently running a classic version of Rails? find_all does not operate in recent versions: 'find(:all)' or simply 'all' would be the techniques nowadays.

File.new("#{RAILS_ROOT}/mls_widget_config.xml", "w") do |f|
  Carrier.all.each { |carrier| f.puts carrier.to_xml }