【问题标题】:Handling recurring tasks in Rails处理 Rails 中的重复任务
【发布时间】:2018-03-26 13:33:26
【问题描述】:

我一直在尝试构建一个可以添加重复任务的自定义待办事项应用程序。

我的第一个方法是在前面使用 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

我想知道是否有比使用宝石更好的方法来处理它?我正在阅读有关安排 rake 任务的信息,但我自己从来没有做过,所以我不确定这是否也是可行的方法。

提前致谢。

【问题讨论】:

    标签: ruby-on-rails ruby recurring-events ice-cube


    【解决方案1】:

    是的,使用 rake 任务和 whenever gem 执行重复任务有更好的方法。它有一个非常易于使用的 DSL

    您需要做的就是定义您的 rake 任务,然后将调度配置放在 schedule.rb 中。

    但是,只要使用 cron 作业并且 Heroku 不支持。如果你使用 Heroku,那么你应该使用Heroku Scheduler。您需要做的就是在 tasks/scheduler.rake 中定义您的任务,安装插件,然后让 Heroku Scheduler 完成剩下的工作。

    这种方法将有助于保持您的模型更清洁并从中删除调度信息。

    对于将重复任务标记为完成的问题的第二部分,您需要做的就是在重复任务被标记为完成时将布尔属性设置为 completed 为 true,然后在您的像 return if task.completed? 这样的 rake 任务以跳过该任务的处理。

    【讨论】:

    • 谢谢@Nwocha。关于我的问题的第二部分,尽管问题是由于冰块时间表仅显示内存中存在的元素,而不是在您的数据库中,但将始终链接回原始任务,因此您无法更新事件的属性.我最终使用了 ActiveJob,并且只使用 ice-cube 调度信息来有条件地调度任务复制。
    猜你喜欢
    • 2011-08-23
    • 2012-02-12
    • 2013-08-30
    • 2012-02-07
    • 2013-03-07
    • 1970-01-01
    • 2017-09-30
    • 2020-04-14
    • 1970-01-01
    相关资源
    最近更新 更多