What's the best way to model recurring events in a calendar application?

后端 未结 18 2481
感情败类
感情败类 2020-11-27 08:54

I\'m building a group calendar application that needs to support recurring events, but all the solutions I\'ve come up with to handle these events seem like a hack. I can li

18条回答
  •  粉色の甜心
    2020-11-27 09:16

    I'd recommend using the power of the date library and the semantics of the range module of ruby. A recurring event is really a time, a date range (a start & end) and usually a single day of the week. Using date & range you can answer any question:

    #!/usr/bin/ruby
    require 'date'
    
    start_date = Date.parse('2008-01-01')
    end_date   = Date.parse('2008-04-01')
    wday = 5 # friday
    
    (start_date..end_date).select{|d| d.wday == wday}.map{|d| d.to_s}.inspect
    

    Produces all days of the event, including the leap year!

    # =>"[\"2008-01-04\", \"2008-01-11\", \"2008-01-18\", \"2008-01-25\", \"2008-02-01\", \"2008-02-08\", \"2008-02-15\", \"2008-02-22\", \"2008-02-29\", \"2008-03-07\", \"2008-03-14\", \"2008-03-21\", \"2008-03-28\"]"
    

提交回复
热议问题