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

时间:2017-01-26 00:15:28

标签: ruby-on-rails ruby-on-rails-4 actionviewhelper

我在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无效。

2 个答案:

答案 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

这是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

答案 1 :(得分:0)

我更喜欢即时添加:

date_helpers = Class.new {include ActionView::Helpers::DateHelper}.new
time_ago = date_helpers.time_ago_in_words(some_date_time)