从/lib目录中定义的类访问ActionView::Helpers::DateHelper



我在/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_wordsActionView::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

这就是includeextend之间的区别。

或者

你可以这样调用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)

最新更新