简体   繁体   中英

What's the correct way to reference a helper in a rails controller?

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
  • Avoid view_context it instantiates a view instance per call and assumes you're necessarily using ActionView
  • Avoid self.class.helpers.myhelper since this'll need to perform reflection to determine the current class
  • Avoid 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM