2011-12-30 67 views
0

我必須丟失一些關於運算符& &的紅寶石(我懷疑是這種行爲的原因)?RoR 3:代碼在before_filter和控制器動作中行爲不一樣

此編號: 匿名& & user_signed_in? 不會生成它在application_controller的before_filter中或家庭控制器的操作中的輸出。

而我不明白爲什麼。

詳細說明:

我在應用控制器中加入此代碼和它會運行爲的before_filter

anonymous = cookies['anonymous'] 
fresh_session = cookies['session_id'].nil? 
rep = (fresh_session || (anonymous && user_signed_in?)) 
puts "REPONSE : #{rep} session: #{fresh_session} anonym #{anonymous} is there a curr user: #{user_signed_in?} /// BOTH: #{(anonymous && user_signed_in?)}" 

印刷resulte是:

REPONSE : true session: false anonym false is there a curr user: true /// BOTH: true 

如果相同的代碼在家庭控制器 th的動作中e打印結果是:

REPONSE : false session: false anonym false is there a curr user: true /// BOTH: false 

請幫我理解。

編輯(以下Klochne的要求):

在app_controller:

Anon-class: String REPONSE : true session: false anonym false is there a curr user: true /// BOTH: true 

在home_controller

Anon-class: FalseClass REPONSE : false session: false anonym false is there a curr user: true /// BOTH: false 

所以一個解釋爲出於某種原因的字符串。

+0

添加此並在兩個地方嘗試:「anon-class:#{anonymous.class.name}」 – klochner 2011-12-30 18:48:36

+0

在您調用代碼以檢索/打印它之前,某事物已將Cookie ['anonymous']設置爲'false'在home_controller中,而在ApplicationController中調用它時將它設置爲一個字符串。這與'&&'操作符無關。 – Batkins 2011-12-30 21:47:52

+0

我希望它是這樣的,但沒有任何設置的cookie,只有一個地方,我明確地將其設置爲false或true。 – Emanuel 2011-12-30 23:52:13

回答

0

嘗試將before過濾器中的變量設置爲實例變量而不是局部變量。這樣他們將堅持並保持設置在控制器操作中,而不是實例變量。所以,改變方法被調用的before_filter是這樣的:

@anonymous = cookies['anonymous'] 
@fresh_session = cookies['session_id'].nil? 
@rep = (fresh_session || (anonymous && user_signed_in?)) 
puts "REPONSE : #{@rep} session: #{@fresh_session} anonym #{@anonymous} is there a curr user: #{user_signed_in?} /// BOTH: #{(@anonymous && user_signed_in?)}" 

然後在你的控制器,你可以只需再次把這個行:

puts "REPONSE : #{@rep} session: #{@fresh_session} anonym #{@anonymous} is there a curr user: #{user_signed_in?} /// BOTH: #{(@anonymous && user_signed_in?)}" 

它應該打印出相同的結果。 Local variables are only accessible from within the block of its initialization

相關問題