RailsCast #213 Calendars(修订版)是关于制作一个显示published_on
博客帖子日期的日历。在views/articles/index.html
,作者把这段代码:
<%= calendar @date do |date| %>
<%= date.day %>
<% end %>
这调用了他包含在calendar_helper.rb
. 这适用于 Rails 3.2 应用程序,但是当我尝试在 Rails 4 应用程序中使用它时,我只得到一个空白页。我puts
在方法中添加了语句table
:
def table
content_tag :table, class: "calendar" do
puts header
puts week_rows
header + week_rows
end
end
并且日历打印到服务器日志,但页面上仍然没有显示任何内容。这段代码有什么东西使它在带有 Ruby 2 的 Rails 4 中过时了吗?
module CalendarHelper
def calendar(date = Date.today, &block)
Calendar.new(self, date, block).table
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 table
content_tag :table, class: "calendar" do
header + week_rows
end
end
def header
content_tag :tr do
HEADER.map { |day| content_tag :th, day }.join.html_safe
end
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 :td, view.capture(day, &callback), class: day_classes(day)
end
def day_classes(day)
classes = []
classes << "today" if day == Date.today
classes << "notmonth" 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
end
end