7

Possible Duplicate:
Access a view helper for a model in rails

I know this is probably not something I should do often, but I want to use a helper within a model.

I'm generating a spreadsheet in a Report model and would like to use the time_ago_in_words method in ActionView::Helpers::DateHelper

Is this doable, or should I be generating it in a view?

Community
  • 1
  • 1
Joe Flynn
  • 6,908
  • 6
  • 31
  • 44
  • Duplicate? http://stackoverflow.com/search?q=rails+helper+in+model – Smar Jul 25 '11 at 18:25
  • 1
    actually, this is precisely what I was looking for. The search query implying that this is a duplicate did not turn up anything as helpful. – Douglas Lovell Oct 19 '13 at 19:42
  • 1
    This works better for me: `ApplicationController.helpers.my_helper_method` Source: http://makandracards.com/makandra/1307-how-to-use-helper-methods-inside-a-model – skozz Jul 16 '14 at 15:58

2 Answers2

17

You can just include the module in the model, and use it like you would in a view

class Report
  include ActionView::Helpers::DateHelper
  ...
end
Joe Flynn
  • 6,908
  • 6
  • 31
  • 44
  • 5
    What if you only want to use one method from the helper module, and you don't want to `include` the whole thing? Is that possible? – Jared Beck Jul 25 '16 at 19:10
0
class Post < ActiveRecord::Base
  include ActionView::Helpers::DateHelper

  def my_test_method(a, include_seconds = false)
    time_ago_in_words(a, include_second)
  end

 end
awilkening
  • 1,062
  • 8
  • 26