kddeisz
kddeisz

Reputation: 5202

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:

Upvotes: 1

Views: 745

Answers (1)

fny
fny

Reputation: 33635

  • 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 since this'll make all the helper methods controller actions

Upvotes: 1

Related Questions