【发布时间】:2011-11-16 14:26:42
【问题描述】:
我们的 Rails 项目大量使用 content_for。但是,如果没有使用 content_for 定义任何内容,我们经常需要呈现默认内容。为了可读性和可维护性,将此默认内容放在一个块中是有意义的。
我们在 Rails 2.3 中创建了一个辅助方法,现在我们为 Rails 3 重构了它(如下所示)。
这两个助手都工作得很好,但我想知道是否有更简洁的方法可以在 Rails 3 中实现相同的目标。
导轨 2.3:
def yield_or(name, content = nil, &block)
ivar = "@content_for_#{name}"
if instance_variable_defined?(ivar)
content = instance_variable_get(ivar)
else
content = block_given? ? capture(&block) : content
end
block_given? ? concat(content) : content
end
这对于做这样的事情很有用:
<%= content_for :sidebar_content do %>
<p>Content for the sidebar</p>
<% end %>
<%= yield_or :sidebar_content do %>
<p>Default content to render if content_for(:sidebar_content) isn't specified</p>
<% end %>
为 Rails 3 重构:
def yield_or(name, content = nil, &block)
if content_for?(name)
content_for(name)
else
block_given? ? capture(&block) : content
end
end
【问题讨论】:
-
可爱的小帮手(“为 Rails 3 重构”)
标签: ruby-on-rails-3