Skip to content

Instantly share code, notes, and snippets.

@andreorvalho
Created June 25, 2014 13:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save andreorvalho/fdb28af8284b13fc9829 to your computer and use it in GitHub Desktop.
Save andreorvalho/fdb28af8284b13fc9829 to your computer and use it in GitHub Desktop.
calendar helper
# taken from http://railscasts.com/episodes/213-calendars-revised
module CalendarHelper
def calendar(date = Date.today, type = :list, &block)
Calendar.new(self, date, type, block).table
end
class Calendar < Struct.new(:view, :date, :type, :callback)
HEADER = %w[Man Tir Ons Tor Fre Lør Søn]
START_DAY = :monday
delegate :content_tag, to: :view
def table
content_tag calendar_tag_for_type, class: "calendar-list" do
type.to_sym == :list ? header + whole_month_in_weeks : header_rows + week_rows
end
end
private
def header
HEADER.map { |day| content_tag :li, day, class: header_classes }.join.html_safe
end
def header_rows
content_tag :tr do
HEADER.map { |day| content_tag :th, day }.join.html_safe
end
end
def whole_month_in_weeks
weeks.map { |day| day_cell(day) }.join.html_safe
end
def week_rows
weeks.map do |week|
content_tag :tr do
week.map { |day| day_cell(day) }.join.html_safe
end
end.join.html_safe
end
def day_cell(day)
content_tag day_tag_for_type, view.capture(day, &callback), class: day_classes(day)
end
def weeks
first = date.beginning_of_month.beginning_of_week(START_DAY)
last = date.end_of_month.end_of_week(START_DAY)
weeks = (first..last).to_a
type.to_sym == :list ? weeks : weeks.in_groups_of(7)
end
def header_classes
classes = []
classes << "calendar-list-item"
classes.empty? ? nil : classes.join(" ")
end
def day_classes(day)
classes = ["day", "calendar-list-item"]
classes << "current-day" if day == Date.today
classes << "weekend" if weekend?(day)
classes << "other-month" if day.month != date.month
classes.empty? ? nil : classes.join(" ")
end
def weekend?(day)
day.saturday? || day.sunday?
end
def calendar_tag_for_type
type.to_sym == :list ? :ul : :table
end
def day_tag_for_type
type.to_sym == :list ? :li : :th
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment