如何使整成日期的数组? [英] How to make integer into array of dates?

查看:145
本文介绍了如何使整成日期的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个用户创建了 days_challenge一个挑战:5 &安培; 承诺:星期一,星期二,星期三,星期四,星期五] 那么如何才能从创建日期的数组 date_started:二○一六年四月二十〇日,直到使用一个被称为模型法的挑战的最后一天 dates_challenged

If a user creates a challenge with days_challenge: 5 & committed: ["mon", "tue", "wed", "thu", "fri"] then how can we create an array of dates from date_started: "2016-04-20" until the last day of the challenge using a model method called dates_challenged?

create_table "challenges", force: true do |t|
  t.string   "action"
  t.date     "date_started"
  t.text     "committed",       default: "---\n- sun\n- mon\n- tue\n- wed\n- thu\n- fri\n- sat\n"
  t.integer  "days_challenged"
end

该数组将是这个样子: [2016年4月20日,2016年4月21日,2016年4月22日,2016年4月25日 2016年4月26日]

class Challenge < ActiveRecord::Base
  serialize :committed, Array

  def dates_challenged
    # Not sure if a model method is enough or if I'd have to migrate a new column
  end

  def committed_wdays
    committed.map do |day|    
      Date::ABBR_DAYNAMES.index(day.titleize)
    end
  end

  def days_left_challenged
    def days_done_challenged
      ((date_started.to_date)..Date.yesterday).count do |date| 
        committed_wdays.include? date.wday
      end
    end  
    if self.days_done_challenged >= self.days_challenged
      0
    else
      self.days_challenged - ((date_started.to_date)..Date.yesterday).count do |date| 
        committed_wdays.include? date.wday
      end
    end
  end
end

要澄清一下,我试图做一个模型的方法,所以我可以在一个视图,然后我就可以遍历日期的阵列做 @ challenge.dates_challenged

To clarify, I'm trying to make a model method so I could do @challenge.dates_challenged in a view where I can then iterate over the array of dates.

推荐答案

这是我想出了 - 还存在一些问题 - 我想,如果致力于是空的,但它是很好的,简洁的:

This is what I came up with - there are still some issues - I think it will blow up if committed is empty, but it's nice and concise:

def dates_challenged
  date = date_started-1
  days_challenge.times.map { date = find_next(date) }
end

private
def find_next(date)
  break if committed.include? Date::ABBR_DAYNAMES[date.wday].downcase while date = date.next
  date
end

这篇关于如何使整成日期的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆