我有一个日历,显示本月的公共活动。这是一个响应式布局,所以我需要能够计算week_row高度。因此,我需要能够计算当月的周数,包括部分周数(包含当月和上个月/下个月的天数的周数)。
以下方法计算当月的周数:
def weeks_in_month(date)
@week_count = (0.5 + (date.end_of_month.day + date.beginning_of_month.wday).to_f / 7.0).round
end
并且将适当的类添加到<div>
的代码是:
def week_rows
weeks.map {|week|
content_tag :div, class: week_classes(week) do
week.map { |day| day_cell(day) }.join.html_safe
end
}.join.html_safe
end
def week_classes(date)
classes = ['week']
classes << "wk_rows_4" if weeks_in_month(date) == 4
classes << "wk_rows_5" if weeks_in_month(date) == 5
classes << "wk_rows_6" if weeks_in_month(date) == 6
classes.empty? ? nil : classes.join(" ")
end
然而,我错过了一些东西。 week_classes不会填充默认'week'
类以外的任何内容。
这是基于RailsCasts#213,在创建没有表格的日历时根据this tutorial进行了修改,这也是RC#231的大量借鉴。
知道为什么它没有为<div>
分配正确的课程?
日历中的其他所有内容都有效。这是完整的代码:
module CalendarHelper
def calendar(date = Date.today, &block)
Calendar.new(self, date, block).calendar_div
end
class Calendar < Struct.new(:view, :date, :callback)
HEADER = %w[Sunday Monday Tuesday Wednesday Thursday Friday Saturday]
START_DAY = :sunday
delegate :content_tag, to: :view
def calendar_div
content_tag 'div', id: "calendar" do
header + week_rows
end
end
def header
content_tag 'div', id: 'weekdays' do
HEADER.map { |day| content_tag :div, class: 'weekday' do
day
end }.join.html_safe
end
end
def week_rows
weeks.map {|week|
content_tag :div, class: week_classes(week) do
week.map { |day| day_cell(day) }.join.html_safe
end
}.join.html_safe
end
def week_classes(date)
classes = ['week']
classes << "wk_rows_4" if weeks_in_month(date) == 4
classes << "wk_rows_5" if weeks_in_month(date) == 5
classes << "wk_rows_6" if weeks_in_month(date) == 6
classes.empty? ? nil : classes.join(" ")
end
def day_cell(day)
content_tag :div, view.capture(day, &callback), class: day_classes(day)
end
def day_classes(day)
classes = ['day']
classes << "today" if day == Date.today
classes << "notmonth" if day.month != date.month
classes << "month" if day.month == date.month
classes.empty? ? nil : classes.join(" ")
end
def weeks
first = date.beginning_of_month.beginning_of_week(START_DAY)
last = date.end_of_month.end_of_week(START_DAY)
(first..last).to_a.in_groups_of(7)
end
def weeks_in_month(date)
@week_count = (0.5 + (date.end_of_month.day + date.beginning_of_month.wday).to_f / 7.0).round
end
end
答案 0 :(得分:0)
好的,所以一些摆弄让我想到这个解决方案:
def week_rows
weeks.map {|week|
content_tag :div, class: week_classes do
week.map { |day| day_cell(day) }.join.html_safe
end
}.join.html_safe
end
def week_classes
classes = ['week']
classes << "wk_rows_4" if weeks_in_month == 4
classes << "wk_rows_5" if weeks_in_month == 5
classes << "wk_rows_6" if weeks_in_month == 6
classes.empty? ? nil : classes.join(" ")
end
def weeks_in_month
(0.5 + (date.end_of_month.day + date.at_beginning_of_month.wday).to_f / 7.0).round
end
没有必要传递(date)
作为参数。