簡體   English   中英

如何解決無法從控制器的 class 方法調用 controller 方法的問題?

[英]How do I work around not being able to call a controller method from a controller's class method?

我正在使用具有兩種方法的 Rails controller:

...

protected
  def self.some_method
    ...
    another_method
    ...
  end

  def another_method
    ...
  end

我希望能夠從self.some_method調用another_method 不幸的是,我得到:

undefined method `another_method' for MyNamespace::MyController:Class

我認為這與一種方法有關,即 class 方法。 我的目標是避免代碼重復,因為我還需要在常規 controller 操作中使用another_method

有沒有更好的地方可以放置another_method以便self.some_method和常規 controller 操作都可以使用? 它需要在 controller 中,因為我需要訪問current_user

如果您希望能夠從 class 方法調用another_method ,那么您不能在其中使用任何實例 state。 因此,您也可以將其定義為 class 方法,或者將其放在完全不同的位置(如 util function 模塊:

module Utils
  module_function

  def another_method
    ...
  end
end


class MyController
  def self.some_method
    ...
    Utils.another_method
    ...
  end
end

我可以看到some_method是如何結束的,它覆蓋了 Rails 自己的一些 class 方法。 但是同樣,您不會在其中包含任何實例 state,因此如果您需要每個實例具有不同的行為(例如訪問請求),那么您很不走運,您需要找到另一種方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM