(Herokuスケジューラを使用して)毎晩実行されるrakeタスクを使用し、特定の基準が満たされた場合にいくつかの属性を更新しようとしています。
アプリケーションに関する小さなロジック:
このアプリケーションを使用すると、ユーザーは「チャレンジ」して、1年間で1週間にわたって本を読むことができます。非常に簡単です。ユーザーはサインアップして、最初の週に読む最初の本を作成し、次の週に読む予定の本を入力できます。彼らが来週の本を「キューに入れ」た後、最初の本が作成されてから7日が経過するまで、そのフォームは非表示になります。その時点で、キューに入れられた本はリストの一番上に移動し、「現在読んでいる」とマークされ、前の「現在読んでいる」本はリストの2番目の位置に移動します。
また、ユーザーが本を「キューに入れる」ことがない場合、最新の「現在読んでいる」本が作成されてから7日が経過すると、システムは自動的に本を作成します。
アドバイスが必要なところ
私が現在立ち往生している場所は、最後の「現在読んでいる」本が作成されてから7日が経過している場合に、本に属性を更新させることです。以下は私の本のモデルであり、メソッドupdate_queue
はレーキタスク中に呼び出されるものです。現在、rakeタスクを実行してもエラーは発生せず、コードを適切にループしますが、属性値は変更されません。そのため、メソッドのコードが行のどこかで正しくないことを確信してupdate_queue
います。その理由のトラブルシューティングにご協力いただければ幸いです。そして、これをテストする方法は、本を追加してから、システムの日付を8日前に手動で変更することです。かなり野蛮ですが、このアプリケーション用に作成されたテストスイートはありません。これが、私にとって最も簡単な方法です:)
class Book < ActiveRecord::Base
attr_accessible :author, :date, :order, :title, :user_id, :status, :queued, :reading
belongs_to :user
scope :reading_books, lambda {
{:conditions => {:reading => 1}}
}
scope :latest_first, lambda {
{:order => "created_at DESC"}
}
def move_from_queue_to_reading
self.update_attributes(:queued => false, :reading => 1);
end
def move_from_reading_to_list
self.update_attributes(:reading => 0);
end
def update_queue
days_gone = (Date.today - Date.parse(Book.where(:reading => 1).last.created_at.to_s)).to_i
# If been 7 days since last 'currently reading' book created
if days_gone >= 7
# If there's a queued book, move it to 'currently reading'
if Book.my_books(user_id).where(:queued => true)
new_book = Book.my_books(user_id).latest_first.where(:queued => true).last
new_book.move_from_queue_to_reading
Book.my_books(user_id).reading_books.move_from_reading_to_list
# Otherwise, create a new one
else
Book.my_books(user_id).create(:title => "Sample book", :reading => 1)
end
end
end
私のrakeタスクは次のようになります(lib /tasksに配置されたscheduler.rake):
task :queue => :environment do
puts "Updating feed..."
@books = Book.all
@books.each do |book|
book.update_queue
end
puts "done."
end