我正在尝试创建一个日历表来显示公司每位员工的每日可用性。我认为我需要的是一个标题,其中包含每月的日期,然后是每个工作人员的一行(具有与天数一样多的单元格)。每个单元格的不同背景颜色将代表不同的可用性状态,并且工作人员会更改,因此我希望动态生成所有这些。
在线研究并以Ryan Bates' Railscast #213 (Calendars Revised)作为我的向导后,我到目前为止设法生成表格的标题,显示每个单元格中每月的日期。
到目前为止,这是我的代码:
module ReceptionHelper
def reception(date = Date.today, &block)
Reception.new(self, date, block).table
end
class Reception < Struct.new(:view, :date, :callback)
delegate :content_tag, to: :view
def table
content_tag :table, class: "calendar" do
daysHeader
end
end
def daysHeader
last_day = date.end_of_month.strftime("%d").to_i
(0..last_day).to_a.map { |day| content_tag :th, day }.join.html_safe
end
end
现在,问题和困惑开始了:
正如我所发现的,正在删除&block
和:callback
会取消{...}功能。我不能说我理解为什么。有没有好解释的人?
为什么上述工作有效,但我无法使用下面的(..).each do
和content_tag
块?
(0..last_day).to_a.each do |day|
content_tag :th do
day
end
end
在我努力为每位员工显示行时,我选择了这个:
def table
content_tag :table, class: "calendar" do
daysHeader + staffRows
end
end
def staffRows
staff.to_a.map { |staff| content_tag :tr, staff.name }.join.html_safe
end
我在staff
课程定义中添加了Reception
,并且我使用<%= reception @staff %>
进行了调用 - 如果这不是一个非常好的做法,请随时对我大喊:D
但是,我不是每个工作人员获得一行,而是将所有成员名称放在一行中并且在标题的正上方。将content_tag :tr
更改为content_tag :td
会导致在最后一个标题单元格后面包含每个职员名称的单元格。
正如你所理解的那样,我对此感到非常迷茫,似乎我甚至没有清楚地知道为什么那些按照我的要求运作的部分是正确的。我希望这篇文章不会给人留下这样的印象:我希望把所有东西都送到我的盘子里 - 我宁愿寻找能帮助我理解的方向。 :)
修改
我通过将staffRows
方法更改为此来取得了一些进展:
def staffRows
staff.to_a.in_groups_of(1).map do |staff|
content_tag :tr do
staff.map { |room| content_tag :th, staff.name }.join.html_safe
end
end.join.html_safe
end
然而,每个房间只生成一个单元格,而我想要一个单元格与标题一样多的行。
答案 0 :(得分:6)
首先是ruby约定:使用2个空格作为间距,并使用_作为方法名称。
现在在写复杂的帮助者时遇到你最好的朋友:concat
。它的作用是将字符串直接输出到ERB缓冲区。向您展示和示例:
def my_helper
concat "hello world"
end
<% my_helper %>
即使我们使用hello world
而非<%
,也会在html中输出<%=
。
在处理帮助程序中的块时这是非常重要的方法,因为这意味着您可以在块中多次调用concat
并输出两个字符串。这是一个例子:
def my_helper
content_tag :div do
concat "Hello "
concat "World"
concat "!"
end
end
<%= my_helper %>
会输出<div>Hello World!</div>
。所以使用相同的想法你可以做这样的事情:
def my_helper
content_tag :ul do
@people.each do |person|
concat content_tag(:li, person.name)
end
end
end
<%= my_helper %>
会产生类似这样的结果:<ul><li>John Doe</li><li>Mike Tyson</li></ul>
。
所以我会将days_helper
改写成这样的东西:
def days_header
(0..date.end_of_month.day).each { |day| concat content_tag(:th, day) }
end
使用staff_rows
方法执行类似操作,然后table
方法看起来就像这样:
content_tag :table, class: "calendar" do
days_header
staff_rows
end
至于问题的回调部分:&block
捕获传递给方法的块到Proc对象。以后可以将此对象传递给其他方法或直接调用。由于你没有使用回调对象,我只是建议删除它。