我在EmailHelper
中定义了/lib/email_helper.rb
个类。该类可以由控制器或后台作业直接使用。它看起来像这样:
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
如何从time_ago_in_words
课程的上下文中访问EmailHelper
辅助方法?请注意,我已经包含了相关模块。
我也尝试过调用helper.time_ago_in_words
和ActionView::Helpers::DateHelper.time_ago_in_words
无效。
答案 0 :(得分:1)
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
答案 1 :(得分:0)
我更喜欢即时添加:
date_helpers = Class.new {include ActionView::Helpers::DateHelper}.new
time_ago = date_helpers.time_ago_in_words(some_date_time)