2017-10-14 71 views
0

我一直在嘗試構建一個可定製的待辦事項應用程序,以添加重複性任務。在Rails中處理循環任務

我的第一種方法是使用前面的recurring_select和後面的ice_cube邏輯。我設法生成了一個包含所有期望事件的時間表,但我遇到的問題是,這樣我就不能再次將重複性任務標記爲完整的,因爲它只是它的顯示事件。

下面是一些代碼:

*task.rb* 
class Task < ApplicationRecord 
    (...) 
    serialize :recurrence, Hash 

    def recurrence=(value) 
    # byebug 
    if value != "null" && RecurringSelect.is_valid_rule?(value) 
     super(RecurringSelect.dirty_hash_to_rule(value).to_hash) 
    else 
     super(nil) 
    end 
    end 

    def rule 
    IceCube::Rule.from_hash recurrence 
    end 

    def schedule(start) 
    schedule = IceCube::Schedule.new(start) 
    schedule.add_recurrence_rule(rule) 
    schedule 
    end 

    def display_tasks(start) 
    if recurrence.empty? 
     [self] 
    else 
     start_date = start.beginning_of_week 
     end_date = start.end_of_week 
     schedule(start_date).occurrences(end_date).map do |date| 
      Task.new(id: id, name: name, start_time: date) 
     end 
    end 
    end 
end 

*tasks_controller.rb* 
class TasksController < ApplicationController 
    before_action :set_task, only: [:complete, :uncomplete, :show] 
    (...) 
    def index 
    (...) 

    @display_tasks = @tasks.flat_map{ |t| t.display_tasks(params.fetch(:start_date, Time.zone.now).to_date) } 
    end 
    (...) 
end 

我想知道是否有可能是更好的方式來處理它比使用寶石?我正在閱讀有關安排耙架任務的內容,但我從來沒有做過,所以我不確定是否要這樣做。

在此先感謝。

回答

1

是的,有更好的方法來使用rake任務和whenever gem執行循環任務。它有一個非常容易使用的DSL

您只需要定義您的rake任務,然後將schedule配置放入schedule.rb中。

但是,每當使用cron作業並且不受Heroku支持時。如果您使用的是Heroku,那麼您應該使用Heroku Scheduler。您只需要在任務/計劃程序.rake中定義您的任務,安裝插件並讓Heroku Scheduler完成其餘任務。

這種方法將有助於保持模型清潔並從中刪除調度信息。

對於問題的第二部分,將循環任務標記爲完成,只需將布爾屬性設置爲completed爲true,此時將循環任務標記爲完成,然後在您的耙子中添加警戒子句像return if task.completed?這樣的任務跳過該任務的處理。

+0

謝謝@Nwocha。關於我的問題的第二部分,雖然問題是由於冰塊計劃僅顯示內存中的一個元素,而不是在您的數據庫中,但始終會鏈接回原始任務,因此您無法更新事件的屬性。 我最終使用ActiveJob並使用冰塊調度信息僅用於有條件地調度任務重複。 –