Created
February 7, 2012 19:34
-
-
Save richardcalahan/1761418 to your computer and use it in GitHub Desktop.
Calendar Generator class prototype
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## NOTE | |
Class assumes event model includes start_date and end_date, | |
both of type 'datetime'. | |
You can init the class with a hash of options. | |
There are two options options at this point, 'month_format', | |
and 'date_format' which accept Ruby's 'strftime' style strings. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Calendar | |
TODAY = { | |
:year => DateTime.now.year, | |
:month => DateTime.now.month, | |
:day => DateTime.now.day, | |
:wday => DateTime.now.wday | |
} | |
attr_accessor :events | |
def initialize events, options={} | |
@events = sort_events(events) | |
@month_format = options[:month_format] || "%B %Y" | |
@date_format = options[:date_format] || "%a %-d" | |
end | |
def generate | |
month_range.collect do |month| | |
st = calendar_start_day(month) | |
en = calendar_end_day(month) | |
dates = (st..en).collect do |date| | |
events = @events.select do |e| | |
e.start_date.strftime("%F") == date.to_s | |
end | |
{ :name => date.strftime(@date_format), | |
:events => events, | |
:date => date } | |
end | |
{ :name => month.strftime(@month_format), | |
:dates => dates } | |
end | |
end | |
def month_range | |
events = @events.uniq_by do |event| | |
event.start_date.month | |
end | |
events.collect! do |e| | |
Date.new(e.start_date.year, e.start_date.month) | |
end | |
end | |
def sort_events events | |
events.sort do |a,b| | |
a.start_date <=> b.start_date | |
end | |
end | |
def days_in_month month, year | |
(Date.new(year, 12, 31) << (12-month)).day | |
end | |
def calendar_start_day date | |
day = Date.new(date.year, date.month) | |
day -= day.wday | |
end | |
def calendar_end_day date | |
day = Date.new(date.year, date.month, days_in_month(date.month, date.year)) | |
day += (6 - day.wday) | |
end | |
def full | |
generate | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Example | |
def index | |
respond_to do |format| | |
format.json do | |
@events = Event.all | |
@cal = Calendar.new @events | |
render :json => @cal.full | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment