2012-07-13 96 views
0

我想在我的application_controller.rb控制器中聲明一個變量,所有控制器都可以訪問該變量。如果可能的話,我希望變量只能在子類中訪問,而不能在其他地方訪問,包括視圖(除非專門傳遞到視圖中)。Rails控制器和涉及繼承的「受保護」變量

我是Ruby和Rails的新手,我不確定變量是否存在「protected」作用域,我已經看到它對函數有作用。我一直無法找到一個簡單的答案,我一直在用我用不同的方式來聲明變量和訪問它們的位置,在我的應用程序中嘗試了一下。這沒有提供任何有關我如何完成這一任務的信息。

任何幫助將不勝感激。

代碼:

class ApplicationController < ActionController::Base 
    protect_from_forgery 
    @admin_name = "AdminUserName" 
    @admin_password = "AdminPassword" 
end 

class ProjectsController < ApplicationController 
    http_basic_authenticate_with :name => @admin_name, :password => @admin_password, :except => [:index, :show] 

    # controller functions here 
end 

這似乎並沒有對我的工作。

回答

1

正如您已經認識到的,像ruby中的變量一樣,受保護的作用域不存在。您可以在Rails中使用instance variable在可供視圖訪問的控制器中設置變量。這是一箇舊的Rails功能,you can use instance variables set in the controller in the views

實例變量得到從實例繼承實例

class A 
    def make_ivar 
    @foo = 'bar' 
    end 
end 

class B < A 
    def get_ivar 
    @foo 
    end 
end 

b = B.new 
b.make_ivar 
b.get_ivar #=> @foo 

但要注意,通過傳遞實例變量的觀點軌is breaking encapsulation,並用它在所有的諧音may not be good practice。最重要的是,replace instance variables with local variables as soon as they land in the views

UPDATE

在你的情況下,使用constants。常量是他們在被定義並得到繼承類的範圍之內,但他們沒有提供各方面的意見,除非調用範圍

class ApplicationController < ActionController::Base 
    protect_from_forgery 
    ADMIN_NAME = "AdminUserName" 
    ADMIN_PW = "AdminPassword" 
end 

class ProjectsController < ApplicationController 
    http_basic_authenticate_with :name => ADMIN_NAME, :password => ADMIN_PW, :except => [:index, :show] 

    # controller functions here 
end 

我猜你不想叫他們的看法。如果你真的想這樣做,你可以這樣做:

ApplicationController::ADMIN_NAME 
+0

你遺漏了遺留部分'class B 2012-07-13 17:04:08

+0

@CasualCoder謝謝! – 2012-07-13 17:05:40

+0

所以,這似乎並沒有爲我工作。我將在一秒內用我的實際代碼更新我的問題,以準確顯示我正在嘗試做什麼。 – KayoticSully 2012-07-13 17:09:33