2014-01-22 28 views
0

我開的的助手頁面altered_beast論壇在GitHub上的一看,只見此代碼:向我解釋一行代碼。 Ruby on Rails的

def recent_topic_activity(topic) 
    return false unless logged_in? 
    return topic.last_updated_at > ((session[:topics] ||= {})[topic.id] || last_active) 
    end 

你能解釋一下我的詳細信息第3行。

  • 這是什麼">"爲。
  • 這種結構如何工作:(session[:topics] ||= {})[topic.id])

    我瞭解該行的第一部分。如果session[:topics]等於0,則空散列指定給它。但我從來沒有見過這樣的()[topic.id]

這裏什麼該網頁:提前git

感謝。 我是新來的紅寶石在軌道上,但不是一個總noob。

+1

'>'比較兩次:是第一次後。如果'topic.id'是3,那麼說,如果'session [:topics]'存在,你有'session [:topics] [3]',否則爲零。最後,你的問題包括'()[topic.id]'。也許這是造成混亂;再看一遍,沒有'()'。 – Matt

+0

()[topic.id]我在說這個(session [:topics] || = {})[topic.id] – kirqe

回答

4

讓重寫3號線要少簡潔。

# set topics hash to load from the session. 
# If nothing in session, use an empty hash 
topics_hash = session[:topics] || {} 

# Look in the topics hash for a specific topic id. 
# if nothing is found, use last_active (whatever that is) 
topic_updated_at = topics_hash[topic.id] || last_active 

# If the topics last_updated_at timestamp is greater than (meaning later in time) 
# than the topic_updated_at we calculated above, return true. Otherwise false. 
return topic.last_updated_at > topic_updated_at 

括號中的數值是第一評估,然後像一個單一的值進行處理。這意味着上述代碼中的任何地方都有一個變量名稱,您可以用將該變量設置爲括號的代碼替換它。所以,這兩條線:

topics_hash = session[:topics] || {} 
topic_updated_at = topics_hash[topic.id] || last_active 

可能成爲一條線,做同樣的事情:

topic_updated_at = (session[:topics] || {})[topic.id] || last_active 

你可以在理論上做那種編碼爲一個完整的程序,最大限度地提高複雜性的每一行。有些人喜歡它。在實踐中,它使得很難理解正在發生的事情。

所以第三行簡單地將所有這些步驟巧妙地壓縮到單個表達式中。也許太聰明瞭。

+0

謝謝。現在我懂了 – kirqe

3

讓我們來分析一下:

topic.last_updated_at > something # this is a comparison therefore 
# will return true or false 

關於something

(session[:topics] ||= {})[topic.id] || last_active # this is an OR (||) 
# expression, it will return either the first part if it is not nil or false 
# otherwise it will return the second part (last_active) 

第一部分是:

(session[:topics] ||= {})[topic.id] # this is accessing a nested hash 
# (session is a hash), with the key `topic.id` 
# 
# if session[:topics] exist, it must be a hash so this is like saying: 
# session[:topics][topic.id] 
# 
# if session[:topics] is nil, then it will be assigned an empty hash 
# which will be accessed