如何在 Rails 模块上启用“请求”



>我在app/helpers/currency_helper.rb中为我的应用程序编写了一个小助手,但其中的一种方法取决于request。似乎request模块中不可用。这是我的代码:

module CurrencyHelper
    def define_currency
        ...
        location = request.location
        ... 
    end
end

我已经在我的模型和应用程序控制器中包含上述模块:

include CurrencyHelper

模块中的所有其他方法都按预期工作正常,但每当我执行define_currency时,我都会收到错误:undefined local variable or method 'request' for #<Voice:0x007ff02d43bc30>

如何使request可从我的模块中使用?或者,我还可以在哪里定义此方法,该方法将在控制器和模型级别都可用?

PS:请注意,我已经尝试在ApplicationController中添加该方法,该方法确实适用于Controllers但不适用于Models

编辑

试图实现的是根据请求位置格式化模型(伪代码,请注意我使用的是地理编码器 gem):

class Model
  ...
  def localize
    ...
    if request.location == "GB"
      self.as_json(method: method_available_for_both_model_and_controller)
    else
      self.as_son(method: another_method)
    end
    ...
  end
  ...
end

模型不应该知道任何关于request的事情,因为它们的寿命不同 - 模型可以在请求完成后访问,或者即使根本没有请求。

因此,每次都从控制器传递它,或者在周围的过滤器或request_store gem 中设置一个线程局部变量,但这样做你应该完全确定你知道什么时候发生了什么。

最新更新