以下代码来自 Ryan Bates 的RailsCasts,他在其中将博客的首页变成了日历,以便文章在几天内显示为链接。以下帮助模块创建日历。我对此代码有两个问题
在
day_cell
方法中,他使用了一种叫做 的方法capture
。我在上面找到了一些文档,但我仍然无法弄清楚捕获在这种情况下是如何工作的。另外,&callback
作为参数传递给捕获的是什么?是否与:callback
传递给 Struct.new 的相同?如果是这样,它是如何进入捕获的?传递给 Struct 的 :callback 是什么?def day_cell(day) content_tag :td, view.capture(day, &callback), class: day_classes(day) end
源代码
module CalendarHelper
def calendar(date = Date.today, &block)
binding.pry
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