2017-03-07 90 views
0

可以在普通的.rb文件中使用session變量,除了控制器嗎?全局有權訪問會話in rails

我使用facebook messenger rails gem構建了一個bot。所有的請求都來到app/bot/listen.rb。在這種listen.rb文件:

require "facebook/messenger" 
extend ActionView::Helpers # I need also the session 
include Facebook::Messenger 

Bot.on :message do |message| 
    session[:demo] = 1 
    puts "Your session number is: #{session[:demo]}" 
end 

模塊:: DelegationError(::的ActionView ::幫手#ControllerHelper會議委託給controller.session,但控制器是零:主)

是否有可能從listen.rb文件中存儲會話中的數據?

回答

1

UserInfo模塊封裝讀/寫用戶對象從/到Thread本地。然後可以將該模塊與其他對象混合以便於訪問。

module UserInfo 
    def session 
    Thread.session 
    end 

    def self.session=(session) 
    Thread.session = session 
    end 
end 

在任何控制器中調用任何操作之前,將調用ApplicationController中設置的before_filter。你可以利用這一點在線程本地的值複製出來的HTTP會話,並將其設置:

class ApplicationController < ActionController::Base 
    before_filter :set_user 

    protected 
    # Sets the current user into a named Thread location so that it can be accessed by models and observers 
    def set_user 
    UserInfo.session = session[:user] 
    end 
end 

在模型類,你需要訪問這些值你可以混入任何點幫助程序模塊,然後使用其方法訪問數據。在這個最後的例子中,我們將UserInfo模塊混入到我們的模型中,並且現在可以訪問current_user方法:

class Account < ActiveRecord::Base 
    include UserInfo 

    after_update :log_audit_change 

    private 
    def log_audit_change 
    Audit.audit_change(current_user, self.id, self.new_balance) 
    end 
end