[英]Create an “includable” Rails controller action within helper
Is it possible to make an includable controller action within a Rails Helper through an included
block? 是否可以通过
included
块在Rails Helper中执行included
控制器动作? I'm thinking something like this: 我在想这样的事情:
module XablauHelper
included do
def my_shared_action
true
end
end
end
Already tried doing it through class.eval
block and through using like a class method ie self.my_shared_action
but no success, I have already found a solution that is making a parent controller with the desired shared actions and inheriting from it, but for the sake of modular design I would like to make it a more "global" approach, so I could gemify my solution and reuse code, any suggestions that doesn't use inheritance? 已经尝试过通过
class.eval
块并通过使用类似class方法( self.my_shared_action
但是没有成功,我已经找到了一种解决方案,该解决方案可以使父控制器具有所需的共享操作并从中继承,但是为了方便起见关于模块化设计,我想使其成为一种更具“全局性”的方法,这样我就可以将我的解决方案精髓化并重用代码,还有不使用继承的建议吗?
Adding controller actions in a helper is probably the wrong choice, as these methods are intended for your views . 在帮助程序中添加控制器操作可能是错误的选择,因为这些方法适用于您的视图 。
Consider using controller concerns instead, and including them where required. 考虑改用控制器关注点,并在需要时包括它们。 For example:
例如:
# 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
Where common controller actions can be shared and the controllers have something in common eg they are all API controllers, also consider using inheritance to achieve this. 在可以共享通用控制器动作且控制器具有某些共同点的地方,例如它们都是API控制器,也可以考虑使用继承来实现这一点。 For example:
例如:
# parent controller
class ApiController < ApplicationController
def my_shared_action
end
end
class SpecificApiController < ApiController
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.