好的,我正在为我的小项目处理 View 。我每天都会做这样的事情:
<li <%= 'class="'+item.status.caption+'"' if %w{ sold, absent }.include?(item.status.caption) %> >
最近,我在Ruby API中发现了一个合适的String方法,叫做quote。 我写的是:
<li <%= 'class='+item.status.caption.quote if %w{ sold, absent }.include?(item.status.caption) %> >
但是应用程序抛出错误,表示它无法识别该方法。那么,是否有适当的方法来进行这种常见的引用(或者甚至使用自定义符号/字符串 :P 进行“某种化”)?类似“surround_with”之类的东西吗?在 Rail API 中没有找到线索。
最佳答案
View 中的逻辑太多了,而且您没有使用 Rails 提供的帮助程序。在 app/helpers
中的 foo_helper.rb 文件中创建一个方法(其中“foo”是您的 Controller 名称):
def display_item(item)
case item.status.caption
when /sold/ then class = 'sold'
when /absent/ then class = 'absent'
else class = nil # You could add more cases here as needed
end
content_tag :li, item.name, :class => class # Or whatever you want shown
end
那么,在您看来,您可以调用<%= display_item(item) %>
而不是所有嵌入的 if
胡言乱语。
(哦,这不是你的问题,但作为额外的练习,还要考虑如何减少 item.status.caption
链接,可以使用 item.sold?
和 item.absent?
等方法,也可以将 status
变成您可以直接测试的东西。Google 搜索“Demeter 法则”以了解为什么这是一个好主意。)
关于ruby-on-rails - Rails 中标签内的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1465025/