On Apr 28, 2006, at 10:41 AM, John T. wrote:
On 4/28/06, Benjamin C. [email protected] wrote:
script/runner can do this for you.
Thanks. I did find reference to that. It looks like it can run a
method of a model(? … Book.dosomething).
You could also run a method available in any classes you have in your
lib directory, since those are automatically loaded when your Rails
app loads. I use this all the time and I keep meaning to move my
custom “model” classes to /lib.
Is it able to run methods of controllers?
No. Your controller methods (aka. actions) only run in the context of
a web request. If you really need to do that, you could use a command-
line tool like curl, or wget, to make an http request into your Rails
app. Personally, I’m not really a fan of this.
I guess that could work with what I have in mind. If it can only
run model-based methods, I suppose I can access other models from
the one I’m running the script for.
Again, don’t think about it as just “model-based” methods. The
methods that you call don’t actually have to do anything with your
model classes, if you don’t want them to. Although, that kind of
thing would be a little strange.
(anyone got any examples out there?)
Sure. Here’s a class I use for performing a data export from the
command line. I use this, largely as a crutch, when I don’t feel like
building an admin interface into one of my survey-esque Rails apps.
require ‘csv’
class DataExport
def self.export_ratings
path = “#{RAILS_ROOT}/tmp/my_export.csv”
count = 0
File.open( path, “w+” ) do |p|
CSV::Writer.generate(p, ‘,’, “\r\n”) do |csv|
csv << Student.cols_to_csv
count += 1
Student.get_completed.each do |student|
courses = student.to_csv_list
courses.each do |course|
count += 1
csv << course
end
end
end
end
count
end
end
In case anyone is wondering about the count variable, I actually use
that for my unit tests on this method. It’s a quick way to make sure
the export file has the correct number of lines, which tells me that
the entire export process has worked. There are also tests on the
Student class method “cols_to_csv” and instance method “to_csv_list”.
-Brian