Access ActionView::Helpers::DateHelper from class defined in /lib directory

1.4k Views Asked by At

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.

2

There are 2 best solutions below

1
luiscrjr On BEST ANSWER

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
0
Blair Anderson On

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)