2

I have an EmailHelper class defined in /lib/email_helper.rb. the class can be used directly by a controller or a background job. It looks something like this:

class EmailHelper
    include ActionView::Helpers::DateHelper

    def self.send_email(email_name, record)
        # Figure out which email to send and send it
        time = time_ago_in_words(Time.current + 7.days)
        # Do some more stuff
    end
end

When time_ago_in_words is called, the task fails with the following error:

undefined method `time_ago_in_words' for EmailHelper

How can I access the time_ago_in_words helper method from the context of my EmailHelper class? Note that I've already included the relevant module.

I've also tried calling helper.time_ago_in_words and ActionView::Helpers::DateHelper.time_ago_in_words to no avail.

Daniel Bonnell
  • 4,817
  • 9
  • 48
  • 88

2 Answers2

3

Ruby's include is adding ActionView::Helpers::DateHelper to your class instance.

But your method is a class method (self.send_email). So, you can replace include with extend, and call it with self , like this:

class EmailHelper
    extend ActionView::Helpers::DateHelper

    def self.send_email(email_name, record)
        # Figure out which email to send and send it
        time = self.time_ago_in_words(Time.current + 7.days)

        # Do some more stuff
    end
end

That's the difference between include and extend.

Or...

you can call ApplicationController.helpers, like this:

class EmailHelper

    def self.send_email(email_name, record)
        # Figure out which email to send and send it
        time = ApplicationController.helpers.time_ago_in_words(Time.current + 7.days)

        # Do some more stuff
    end
end
mrlew
  • 7,078
  • 3
  • 25
  • 28
  • 1
    That makes complete sense now. I overlooked the fact that I was trying to use `time_ago_in_words` within a class method when I normally have used it elsewhere in instance methods. Thanks! – Daniel Bonnell Jan 26 '17 at 20:57
0

I prefer to include this on the fly:

date_helpers = Class.new {include ActionView::Helpers::DateHelper}.new
time_ago = date_helpers.time_ago_in_words(some_date_time)
Blair Anderson
  • 19,463
  • 8
  • 77
  • 114