2014-03-19 48 views
1

我知道我會得到答案,我不應該這樣做,但由於解決問題的具體方法我面臨,我將不得不在我的/lib/example.rb文件中使用會話。 (或至少我認爲我將不得不使用它)如何在我的自定義庫文件中包含會話?

我打電話的動作,這將首先運行(seudo代碼):

module ApplicationHelper 

    def funcion(value) 
    MyClass.use_this(value) 
    end 
end 

,然後我會在我的lib/example.rb

使用
module MyClass 
    # include SessionsHelper # this is not working 

    def self.use_this(value) 
    # I want to be able to use session here. What I need to do that in order to make it work. 
    session[:my_value] = value 
    end 
end 

我應該爲了使用內部MyClass的會議上做(我可以通過變量MyClass.use_this(value,session),但我不想這樣做,

編輯:

我想用這個session實現的目標是我想在多個請求中保留一個值。我正在多次調用Web應用程序,並且希望在下次調用時保留一些值。我通過API調用應用程序,我不應該使用數據庫來保存值。所以我已經留下了會話,文本文件,甚至可能是cookies來實現這一點 - 在多次調用中保持相同的值。

回答

0

爲什麼不把模塊包含在控制器中,然後直接從那裏調用use_this函數?

module MyClass #should probably rename this anyway 
    def use_this(value) 
    session[:my_value] = value 
    end 
end 

class SomeController < ApplicationController 
    include MyClass 

    def some_action 
    ... 
    use_this(the_value) 
    ... 
    end 
end 
+0

我正在使用一些類作爲這兩個類之間的中間類。我沒有提到這個問題,因爲它可能是簡單的,我失蹤 – Aleks

+2

'session'是一個由rails中的控制器基類定義的方法,沒有簡單的方法讓它在課堂外可以訪問而不需要做任何事情像我所做的那樣,或者將它作爲方法參數傳遞。 – Slicedpan

+0

好吧,這是一個答案,可以幫助我(或者至少放棄尋找:))和使用參數或類似的東西。 – Aleks

-1

爲了使用session裏面MyClass的可能是你可以使用實例變量@Session:

module MyClass 
    extend SessionsHelper 

    def self.use_this(value) 
    @session[:my_value] = value 
    end 
end 

module SessionsHelper 
    def some_method 
    @session = ... 
    end 
end 

self.include(模塊)方法使的實例方法(和實例變量)將包含的模塊轉換爲包含模塊的實例方法。

編輯:包括SessionsHelper改爲延長SessionsHelper

self.extend(模塊) - 那類和實例變量的接收器成爲類方法方法這個方法之間會工作。

+0

,因爲use_this是一個類方法,實例變量不會被some_method訪問 – Slicedpan

+0

是的,如果您想將some_method作爲類方法(MyClass),那麼你應該使用'擴展SessionsHelper'而不是'include SessionsHelper'。然後在這些方法之間可以訪問實例變量。 –

相關問題