参考
- Rakeタスクをつくる #Rails - Qiita
- Change to Rake tasks and argument structure in Rails 3.2? - Stack Overflow
タスク作成
rails g task send_mail
----------
create lib/tasks/send_mail.rake
----------
- lib/tasks/send_mail.rake
namespace :send_mail do
desc "メール送信"
task :mail_magazine, [:target, :id] => :environment do |task, args|
target = args[:target]
id = args[:id]
mail_maga = MailMagazine.where( id: id ).first
raise "MailMagazine Not Found" if mail_maga.blank?
if target == "all"
users = User.all
users.each_with_index(1) { |user, i|
begin
UserMailer.mail_magazine( user.email, mail_maga ).deliver
puts "[ #{i} : #{user.email} ]"
rescue Exception => e
puts "[ ---------- Exception ---------- ]" ; e.tapp ;
end
}
mail_maga.update_attributes!( target: target, last_sent_at: Time.now )
else
begin
UserMailer.mail_magazine( target, mail_maga ).deliver
result = mail_maga.update_attributes!( target: target, last_sent_at: Time.now )
puts "[ ---------- result ---------- ]" ; result.tapp ;
rescue Exception => e
puts "[ ---------- Exception ---------- ]" ; e.tapp ;
end
end
end
end
- タスク確認
rake -T | grep send_mail:mail_magazine
----------
rake send_mail:mail_magazine[target,id] # メール送信
----------
- ローカル実行
rake send_mail:mail_magazine["aaa@gmail.com",1]
※カンマの後にスペースを入れるとエラー
rake send_mail:mail_magazine["aaa@gmail.com",1] # => OK
rake send_mail:mail_magazine['aaa@gmail.com',1] # => OK
rake send_mail:mail_magazine['aaa@gmail.com', 1] # => NG
rake send_mail:mail_magazine["aaa@gmail.com", 1] # => NG
Heroku
- Heroku用設定
※この設定が無いとモデルが読み込めない「uninitialized constant MailMagazine」エラー
config/environments/production.rb
# Enable threaded mode => For Heroku
config.threadsafe!
config.dependency_loading = true if $rails_rake_task
- Heroku実行
heroku run rake send_mail:mail_magazine["aaa@gmail.com",1]