Following Bate's Railscast (http://railscasts.com/episodes/127-rake-in-background) on background tasks, trying it out with some mailers, not working out for me.
Application controller:
def call_rake(task, options = {})
options[:rails_env] ||= Rails.env
args = options.map { |n, v| "#{n.to_s}='#{v}'" }
system "rake #{task} #{args.join(' ')} --trace 2>&1 >> #{Rails.root}/log/rake.log &"
# need to add path to rake /usr/bin/rake, etc.
end
Request controller:
call_rake :connect_email, :requestrecord => @requestrecord, :lender_array => @lender_array, :item => item, :quantity => quantity
Rake connect_email.rb:
desc "Send email to connect borrower/lender pairs for items found"
task :connect_email => :environment do
RequestMailer.found_email(requestrecord, lender_array, item, quantity).deliver unless lender_array.blank?
end
Am getting error NameError: undefined local variable or method
lender_array' for main:Object. Funny thing is, on a different mailer where the same parameters are passed except for
lender_array, I get an error message
NameError: undefined local variable or method requestrecord' for main:Object
.
Any thoughts on why?
And since it's my first time doing background tasks, would love to get additional insight from smart people on:
- If the environment is being loaded every time this task runs, then isn't that terribly expensive? I mean that means that the environment could be re-loaded several times per hour...
- Ryan mentions it's a good idea to specific the path to rake, e.g.,
/usr/bin/rake
, how do I find what path this is on my local machine and also in production? (using Heroku) - Is it correct to say that what's happening is that Rails is queuing up a list of Rake tasks in the order that they're called by the controller and then once the request is done, just executing them one-by-one?
- None of these error messages are registering in the
rake.log
file I created. Does it only register when the action is completed (i.e., a success)?
I'm just thinking, if person A does the action that calls the rake emails, and then person B does that same action that calls the rake emails a few miliseconds later, will Rails first execute the rake tasks for person A then do the person B request, then do person B's rake tasks, or will it do person A request, person B request, and then do the rake tasks in order received, whenever there is downtime from actual requests?
Thanks!