How to use helper methods inside a model

Updated . Posted . Visible to the public.

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
Last edit
Felix Eschey
License
Source code in this card is licensed under the MIT License.
Posted by Tobias Kraze to makandra dev (2011-06-24 15:38)