在 helper 中创建一个 "includable" Rails 控制器动作

Create an "includable" Rails controller action within helper

是否可以通过 included 块在 Rails 助手中执行可包含的控制器操作?我在想这样的事情:

module XablauHelper
  included do
    def my_shared_action
      true
    end
  end
end

已经尝试通过 class.eval 块并通过使用类似 class 的方法,即 self.my_shared_action 但没有成功,我已经找到了一个解决方案,使父控制器具有所需的共享操作并从中继承,但为了模块化设计,我想让它成为一种更 "global" 的方法,这样我就可以将我的解决方案 gemify 化并重用代码,有没有不使用继承的建议?

helper 中添加 controller 操作可能是错误的选择,因为这些方法适用于您的 views .

考虑改用控制器关注点,并在需要时包括它们。例如:

# in app/controllers/concerns/useful_functions_concern.rb
module UsefulFunctionsConcern
  extend ActiveSupport::Concern

  included do
    rescue_from SomeException, with: :handle_access_denied
  end

  def useful_method
    # ...
  end

  protected
  def handle_access_denied
    # ...
  end
end

# in your controller
class XyzController < ApplicationController
  include UsefulFunctionsConcern

  def index
    useful_method
  end
end

可以共享通用控制器操作并且控制器有一些共同点,例如都是API控制器,也可以考虑用继承来实现。例如:

# parent controller
class ApiController < ApplicationController
  def my_shared_action
  end
end

class SpecificApiController < ApiController
end