Wednesday, November 25, 2009

Calling an authenticated controller action from a rake task

Just wrote that little rake file:

require 'action_controller/integration'

module NoAccessControl
  def has_permission?(rule)
    true
  end
  def logged_in?
    true
  end
end

namespace :reports do
  desc 'Export and email financial reports'
  task :financial => :environment do
    ReportsController.class_eval do
      skip_filter :login_required, :verify_authenticity_token, :role_required
      include NoAccessControl
    end

    sess = ActionController::Integration::Session.new
    sess.post('/reports/financial', :format => 'email', :date => 1.month.ago.end_of_month.strftime('%d/%m/%Y'))
  end
end

I thought that would be useful for some people. It just calls an action from a Rails controller. This action is supposed to be accessed only by the admin user. We also prevent checking for authenticity token. This rake task will be called in a cron job.