2

我有一个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_wordsActionView::Helpers::DateHelper.time_ago_in_words但无济于事。

4

2 回答 2

3

Rubyinclude正在添加ActionView::Helpers::DateHelper到您的类实例中。

但是你的方法是一个类方法self.send_email)。因此,您可以替换includeextend,并调用它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
于 2017-01-26T00:45:59.430 回答
0

我更喜欢动态地包括这个:

date_helpers = Class.new {include ActionView::Helpers::DateHelper}.new
time_ago = date_helpers.time_ago_in_words(some_date_time)
于 2019-09-10T16:16:19.133 回答