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.
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