Skip to content

Instantly share code, notes, and snippets.

@delba
Last active December 17, 2015 09:19
Show Gist options
  • Save delba/5586779 to your computer and use it in GitHub Desktop.
Save delba/5586779 to your computer and use it in GitHub Desktop.
Creating an event with recurring dates
class Event < ActiveRecord::Base
attr_reader :start_date, :end_date, :days
has_many :performances
def build_performances
(start_date..end_date).each do |date|
next unless days.include? date.wday
self.performances << Performance.new(date: date)
end
end
def start_date=(date)
@start_date = Date.parse(date)
end
def end_date=(date)
@end_date = Date.parse(date)
end
def days=(days)
@days = days.map(&:to_i)
end
end
class EventsController < ApplicationController
def new
@event = Event.new
end
def create
@event = Event.new(event_params)
@event.build_performances
@event.performances.each do |p|
logger.info p.date
end
redirect_to :back
end
private
def event_params
params.require(:event).permit(
:name,
:start_date,
:end_date,
days: []
)
end
end
<%= form_for @event do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<% Date::DAYNAMES.each_with_index do |day, i| %>
<%= check_box_tag "event[days][]", i, false, id: day.downcase %>
<%= label_tag day.downcase, day %><br>
<% end %>
<%= f.label :start_date, 'Start Date' %>
<%= f.date_field :start_date %>
<%= f.label :end_date, 'End Date' %>
<%= f.date_field :end_date %>
<%= f.submit %>
<% end %>
require 'date'
class Recurrence
attr_reader :days, :start_date, :end_date
def self.every(*days, options)
new(days, options).dates
end
def initialize(days, options)
self.days = days
self.start_date = options[:from]
self.end_date = options[:to]
end
def days=(days)
@days = days.uniq.map do |day|
Date::DAYNAMES.index day.to_s.capitalize
end
end
def start_date=(date)
@start_date = Date.parse(date)
end
def end_date=(date)
@end_date = Date.parse(date)
end
def dates
(start_date..end_date).select do |date|
days.include? date.wday
end
end
end
Recurrence.every :monday, :tuesday, from: '2013-05-18', to: '2013-06-02'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment