我在/lib/email_helper.rb
中定义了一个EmailHelper
类。该类可以由控制器或后台作业直接使用。它看起来像这样:
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
调用time_ago_in_words
时,任务失败,并出现以下错误:
undefined method `time_ago_in_words' for EmailHelper
如何从EmailHelper
类的上下文中访问time_ago_in_words
助手方法?请注意,我已经包含了相关模块。
我也试过打helper.time_ago_in_words
和ActionView::Helpers::DateHelper.time_ago_in_words
,但都没有用。
Ruby的include
正在将ActionView::Helpers::DateHelper
添加到类实例中。
但是您的方法是类方法(self.send_email
)。因此,您可以将include
替换为extend
,并将其称为self
,如下所示:
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
这就是include
和extend
之间的区别。
或者
你可以这样调用ApplicationController.helpers
:
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
我更喜欢在飞行中包含这个:
date_helpers = Class.new {include ActionView::Helpers::DateHelper}.new
time_ago = date_helpers.time_ago_in_words(some_date_time)