Sometimes I need to use helper methods in controllers (sanitization methods, rendering text back to the view, various other applications). What's the right way? I've got:
self.class.helpers.myhelper
view_context.myhelper
include MyHelper; myhelper
helper MyHelper; myhelper
ActionController::Base.helpers
is the gold standard; you might want to wrap it in a method for convenience:
private def helpers ActionController::Base.helpers end
helper MyHelper
: if you're trying to isolate the helper to the scope of a single controller and don't want to keep typing helpers
all over the place view_context
it instantiates a view instance per call and assumes you're necessarily using ActionView
self.class.helpers.myhelper
since this'll need to perform reflection to determine the current class include MyHelper; myhelper
include MyHelper; myhelper
since this'll make all the helper methods controller actions
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.