Paul Haddad
2006-Aug-11 00:19 UTC
[Rails] Calling a Controller method from the command line
Hi All, I need to run some reports via cron. I know I can use runner and call a method in a model class. But I''d really like to use templates and IMO this kind of logic belongs in a controller anyways. These are periodic reports so I don''t need nor want to leave a server running all the time, so getting the data via curl/wget isn''t really an option. What I really want is script/controller_runner MyController.my_method Any suggestions? -- Paul Haddad (paul.haddad@gmail.com paul@pth.com)
Paul Haddad
2006-Aug-12 20:59 UTC
[Rails] Re: Calling a Controller method from the command line
Hi All, On 8/10/06, Paul Haddad <paul.haddad@gmail.com> wrote:> I need to run some reports via cron. I know I can use runner and call > a method in a model class. But I''d really like to use templates and > IMO this kind of logic belongs in a controller anyways.I never got any responses for this. So I created the below which I hope isn''t a reinvention of the wheel. Stuck it in scripts and now I can cron at will. Not sure if anyone else is interested, but there it is. -- Paul Haddad (paul.haddad@gmail.com paul@pth.com) #!/usr/bin/env ruby begin require File.dirname(__FILE__) + ''/../config/boot'' require ''optparse'' USAGE = "Usage: #{$0} Controller [action] [options]" options = { :environment => (ENV[''RAILS_ENV''] || ''production'').dup } ARGV.options do |opts| opts.banner = USAGE opts.separator '''' opts.on(''-e'', ''--environment=name'', String, ''Specifies the environment for the runner to operate under (test/development/production).'', ''Default: production'') { |v| options[:environment] = v } opts.separator '''' opts.on(''-h'', ''--help'', ''Show this help message.'') { puts opts; exit } opts.parse! end if (ARGV.empty?) puts(USAGE) exit(-1) end ENV[''RAILS_ENV''] = options[:environment] RAILS_ENV.replace(options[:environment]) if defined?(RAILS_ENV) require RAILS_ROOT + ''/config/environment'' require ''application'' include ActionController::TestProcess # Grab the controller class, constantize turns the string into a Class object begin controller_class = ARGV.first.constantize rescue Exception => e $stderr.puts("Couldn''t find controller ''#{ARGV.first}''") exit(-2) end request = ActionController::TestRequest.new response = ActionController::TestResponse.new request.action = ARGV[1] controller_class.process(request, response) if (response.success?) puts(response.body) exit(0) else $stderr.puts(response.body) exit(-3) end rescue SystemExit => e raise # ignore Exit exception rescue Exception => e $stderr.puts(e) exit(-4) end