Helper methods for models in Rails

at. picture at. · Mar 19, 2015 · Viewed 23.9k times · Source

Is there a proper place for helper methods for models in Rails? There are helper methods for controllers and views, but I'm not sure where the best place to put model helper methods. Aside from adding a method to ActiveRecord::Base, which I'd prefer not to.

UPDATE: It seems Concerns make a lot of sense. Here's an example of what I want. Certain models can never be deleted, so I add a callback that always throws an exception:

before_destroy :nope
def nope
  raise 'Deleting not allowed'
end

With concerns, I could do something like this?

class MyModel < ActiveRecord::Base
  include Undeletable
end

module Undeletable
    extend ActiveSupport::Concern

    included do 
      before_destroy :nope 
    end

    def nope
      raise 'Deleting not allowed'
    end
end

Is this the Rails way of doing this?

Answer

Gagan Gami picture Gagan Gami · Mar 19, 2015

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

ApplicationController.helpers.my_helper_method

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

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

via : makandracards's post.

For your reference: http://railscasts.com/episodes/132-helpers-outside-views