在Ruby on Rails中,我们应该使用content_for吗?(:foobar)?

时间:2011-04-19 03:35:59

标签: ruby-on-rails

这适用于Rails 3,几乎总是我认为content_for?(:foo)后跟content_for(:foo)(以haml为单位):

%title= content_for?(:title_for_page) ? "#{content_for(:title_for_page)} - Our great website" : 'Our great website'

因此,不是进行2次查找,而是进行1次查找并使用更长的代码不是更好:

- title_for_page = content_for(:title_for_page)    # is "" when not previously set
%title= title_for_page.blank? ? 'Our great website' : "#{title_for_page} - Our great website"

?但是如果将content_for?实现为哈希,那么无论如何它可能超级快,与blank?相比无论如何?

2 个答案:

答案 0 :(得分:3)

解决问题的单线:

- title_for_page = (c = content_for(:title_for_page)).blank? ? 'Our great website' : "#{c} - Our great website"

答案 1 :(得分:2)

唯一可以找到的方法是测试:)

ruby-1.9.2-p136 :001 > h = {:mike => "test"}
 => {:mike=>"test"} 

ruby-1.9.2-p136 :004 > Benchmark.ms do
ruby-1.9.2-p136 :005 >     h[:mike].present?
ruby-1.9.2-p136 :006?>   end
 => 0.029087066650390625 
ruby-1.9.2-p136 :007 > Benchmark.ms do
ruby-1.9.2-p136 :008 >     h[:mike].blank?
ruby-1.9.2-p136 :009?>   end
 => 0.011205673217773438 

我正在使用present?as per the source of content_for?

有趣的是blank?present?快,不是吗?是时候探索了。

Lets look at the source code for present?:

哇,事实证明present?只是调用blank?并取消它。