How to use helper methods inside a model

Simple

If you want to use a helper_method my_helper_method inside a model, you can write

ApplicationController.helpers.my_helper_method

More flexible

If you need a bit more flexibility, for example if you also need to override some methods, you can do this:

class HelperProxy < ActionView::Base
  include ApplicationController.master_helper_module

  def current_user
    #let helpers act like we're a guest
    nil
  end       

  def self.instance
    @instance ||= new
  end
end

and then use with

HelperProxy.instance.my_helper_method

Bare metal

If you have strong nerves, you can also try to include the ApplicationController.master_helper_module directly into your model.

Tobias Kraze Almost 13 years ago