2010-07-08 67 views
2

我想說明一個帖子作者的姓名; <% @post.author.name %>作品除非作者爲零。所以我要麼使用unless @post.author.nil?要麼添加一個author_name方法來檢查nil,如<% @post.author_name %>。後者我試圖避免。的意見與無處理(在@ post.author.name即無作者)

的問題是,我可能需要添加/刪除取決於是否有一個值或無法言語。例如,如果我簡單地顯示零,「將於1/2/3發佈」將是內容。如果作者爲零,我需要刪除「by」。

+0

問題是我可能需要根據是否有值添加/刪除單詞。 例如,如果我簡單地顯示零,「將於1/2/3發佈」將是內容。如果作者爲零,我需要刪除'by' – Raynard 2010-07-08 21:12:08

回答

3

您可以使用try

<%= @post.author.try(:name) %> 

它將嘗試調用name方法上@post.author,如果它是非零。否則它將返回零,並且不會引發異常。


回答你的第二個問題:原則有什麼不對下列要求:

<% if @post.author %> 
    written by <%= @post.author.name %> 
<% end %> 

<%= "written by #{@post.author.name}" if @post.author %> 

但如果這是一個循環模式,你可能想爲它編寫一個輔助方法。

# app/helpers/authors_helper.rb or app/helpers/people_helper.rb 
class AuthorsHelper 
    def written_by(author) 
    "written by #{author.name}" if author 
    end 
end 

# in your views 
<%= written_by(@post.author) %> 
+0

我不能使用它(請參閱我添加的評論),但它會派上用場,謝謝! – Raynard 2010-07-08 21:12:31

0

編寫一個方法,它接受任何變量並檢查它是否先是nuil,如果它沒有顯示它。那麼你只需要寫一個方法。

6

Null object pattern是爲了避免這種情況的一種方式。在你的課堂上:

def author 
    super || build_author 
end 

這樣你就會得到一個空白的作者,不管是什麼。但是,由於您確實不希望有空對象,所以您確實期望nil,您可以使用某種類型的演示者。

class PostPresenter 
    def initialize(post) 
    @post = post 
    end 

    def post_author 
    (@post.author && @post.author.name) || 'Anonymous' 
    end 
end 

另一種方法是使用try,如@post.author.try(:name),如果你能習慣這一點。

0

,我發現你的問題有趣,因爲我也經常遇到類似的情況,所以我想我會嘗試讓我的第一個Rails插件。

恐怕我還沒有進行任何測試,但你可以試試http://github.com/reubenmallaby/acts_as_nothing(我使用Ruby 1.9.1,所以如果你在評論或Github上遇到任何問題,請告訴我)