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

Access ActionView::Helpers::DateHelper from class defined in /lib directory

我在 /lib/email_helper.rb 中定义了一个 EmailHelper class。 class 可以直接由控制器或后台作业使用。它看起来像这样:

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 class 的上下文中访问 time_ago_in_words 辅助方法?请注意,我已经包含了相关模块。

我也试过拨打 helper.time_ago_in_wordsActionView::Helpers::DateHelper.time_ago_in_words 都无济于事。

Ruby 的 include 正在将 ActionView::Helpers::DateHelper 添加到您的 class 实例 .

但是你的方法是class方法 (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)