Skip to content

Instantly share code, notes, and snippets.

@gouf
Created January 30, 2018 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gouf/a28baca8f7e8ef843ed2f0dacc7e9932 to your computer and use it in GitHub Desktop.
Save gouf/a28baca8f7e8ef843ed2f0dacc7e9932 to your computer and use it in GitHub Desktop.
<table/> タグを用いてカレンダーを生成する
# Ref: * [Railsで今月のカレンダーを生成するerbコード - Qiita](https://qiita.com/nnabeyang/items/8b54a28551983d9cdb32)
# put into... app/helpers/calendar_table_helper.rb
# <table/> タグを用いてカレンダーを生成する
module CalendarTableHelper
def calendar_table_tag(today = Date.today)
tag.table do
calendar_caption(today) +
calendar_header +
calendar_body(today)
end
end
def calendar_header
header = %w(月 火 水 木 金 土 日).map { |wday| content_tag(:th, wday) }
tag.tr(header.join.html_safe)
end
def calendar_caption(today = Date.today)
tag.caption(today.strftime('%Y年%m月'))
end
def calendar_body(today = Date.today)
to_date =
lambda do |date, month|
# 当月でない部分は空白として表示させる
date_string = date.strftime('%m').eql?(month) ? date.strftime('%d') : ' '
# TODO: 条件に応じた表示振り分けをメソッドに切り出し、柔軟性を確保する
if date_string.to_i.odd? && date_string.to_i.zero?.! # 適当な振り分け条件を設定した
tag.span(date_string, class: 'rest-day')
else
tag.span(date_string)
end
end
# その月の初日
this_month = today.at_beginning_of_month.at_beginning_of_week
month = today.strftime('%m')
# その月の1週目から5週目(縦方向の遷移)
1.upto(5).map do
ret =
tag.tr do
(this_month..(this_month.end_of_week)).map do |this_date|
tag.th(to_date.call(this_date, month))
end.join.html_safe
end
this_month += 1.week
ret
end.join.html_safe
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment