2014-01-18 98 views
0

如果我正在討論這個錯誤,請讓我知道我可以改變它。我在config/initializers/payload_signer.rb中有一個文件。我正在試圖在名爲device_enrollment_controller.rb的控制器中使用此文件。Ruby on rails從控制器訪問文件

PayloadSigner.sign(get_profile) 

get_profile是獲取我需要的文件並返回它的控制器中的方法。 PayloadSigner引用其他文件。當我嘗試運行此操作時(記住im確實必須在payload_signer中進行更改,因爲它正常工作),我得到的錯誤是未初始化的常量DeviceEnrollmentController :: PayloadSigner。這導致我相信我正確地引用了payload_signer.rb文件。我已經嘗試過像include和load這樣的東西,但到目前爲止它們都不起作用。

任何幫助或指導表示讚賞。

回答

1

Rails的初始化器控制器模式被調用。所以它不會工作。初始化器不適用於這種用途。相反,我建議將您的代碼放入控制器before_filter。無論是在ApplicationController還是僅在那些需要它的控制器中(例如DeviceEnrollmentController)。事情是這樣的:

class DeviceEnrollmentController # Or ApplicationController 

    before_filter :sign_payload 

    protected 

    def get_profile 
    # Magic 
    end 

    def sign_payload 
    PayloadSigner.sign(get_profile) 
    end 
end 

編輯:又如:

class DeviceEnrollmentController 

    # The filter is only applied to the sign action 
    # (that's what the :only parameter does). 
    before_filter :sign_payload, :only => [:sign] 

    # Browsing to /show, you render this magic button of yours. 
    def show 
    # Render page that holds the button 
    end 

    # The magic button is bound to the /sign route. 
    # Clicking on the button calls this action. 
    def sign 
    # When you get here, the #sign_payload method 
    # has already been called. 
    end 

    protected 

    def get_profile 
    # Magic 
    end 

    def sign_payload 
    PayloadSigner.sign(get_profile) 
    end 
end 
+0

想如果我告訴你,訪問此控制器的特定頁面必須加載,然後你點擊這個仍然成立按鈕。這是什麼讓你簽署的領域。 – Brandon

+0

檢查我的另一個例子,並讓我知道,如果這是你的想法。 – lipanski