2011-09-06 10 views

回答

5

隨着around_filterThread.current[]你可以很容易地創建一個請求上下文/範圍。看下面的例子。

首先添加在您的application_controller.rb

around_filter :request_context 

    def request_context 
    begin 
     RequestContext.begin_request 
     yield 
    ensure 
     RequestContext.end_request 
    end 
    end 

現在下面的類添加到lib/request_context.rb

class RequestContext 
    def self.instance 
    i = Thread.current[:request_context] 
    unless i 
     raise "No instance present. In script/rakefiles: use RequestContext.with_scope {}, " + 
      "in controller: ensure `around_filter :request_scope` is configured" 
    end 
    return i 
    end 

    # Allows the use of this scope from rake/scripts 
    # ContextScope.with_scope do |scope| 
    # # do something 
    # ... 
    # end 
    def self.with_scope 
    begin 
     begin_request 
     yield(instance) 
    ensure 
     end_request 
    end 
    end 

    def self.begin_request 
    raise "request_context already set" if Thread.current[:request_context] 
    Thread.current[:request_context] = RequestContext.new 
    end 

    def self.end_request 
    raise "request_context already nil" unless Thread.current[:request_context] 
    Thread.current[:request_context] = nil 
    end 

    # user part, add constructors/getters/setters here 

    def initialize 
    # you can setup stuff here, be aware that this 
    # is being called in _every_ request. 
    end 
end 

這是非常簡單的。您可以將數據存儲在RequestContext.instance對象中,該對象將在每次請求後重新創建。

1

根據我所知,沒有內置任何內容。對於請求範圍散列的需求在我的書中是一種難聞的氣味。每個請求只有一個關聯的動作,從那裏你應該使用你的模型對象來完成大部分工作。

想想Rails的MVC「請求」管道:

  1. 的瀏覽器向一個URI
  2. Rails的請求查找基於路由信息的控制器和動作
  3. Rails的創建單個該控制器的實例並將該操作作爲方法調用(以任何params []作爲參數)

該單個控制器根據請求創建的troller實例僅限於請求當前的(即,正是你在找什麼)。如果你需要共享請求數據,把它放在你的控制器上,或者更好,把它放在你的行動中,或者甚至更好......在你的模型中。

爲什麼你需要這個?

+0

我有一套會話範圍的數據(顯然與用戶有關),我希望模型有權訪問該數據。我既不擁有控制器或模型,無論是哪種情況我都需要修補控制器/模型。以爲只是修補模型將是最簡單的,因爲它只是一個地方。如果我要改變控制器,那麼需要改變的還有很多。現在我知道模型不能直接訪問會話數據(不喜歡醜陋的工作環境來啓用它)。想知道是否有請求散列,我可以推送會話信息並讓模型從那裏讀取! – thanikkal

+1

做到這一點的「正確」方法是將用戶模型傳遞給任何需要它的模型,無論是作爲參數還是通過關聯。如果您試圖避免更改控制器和模型,並且確信您必須這樣做,我會說讓模型訪問會話數據比讓他們訪問請求數據本質上更糟糕。特別是如果數據已經在會話中。 –

+0

「......我想說讓模型訪問會話數據比讓他們訪問請求數據本質上更糟。」這是一個公平的觀點,我會同意! Lemme重做我的解決方案,以適應「正確」的方式。感謝您的意見 – thanikkal