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

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

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

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

关于ruby-on-rails - 从/lib 目录中定义的类访问 ActionView::Helpers::DateHelper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41864046/

相关文章:

ruby-on-rails - 在 Ruby on Rails 中使用罗马数字、破折号、撇号等标题化

ruby - Rails 渲染 Controller 中的部分和布局

ruby-on-rails - Rails 4.0.2 依赖 mime-types (~> 1.16) 与使用 mime-types 2.0 的其他工具冲突

ruby-on-rails - 渲染 'posts' 和渲染帖子(不带引号)之间的区别

ruby-on-rails - Rails form_tag 表单编写 - 使用非事件记录模型

javascript - rails 4.1.1 : JS file in lib/assets/javascripts doesn't load

ruby-on-rails - 是否可以仅在 RoR3 的特定 View 中强制使用 SSL?

ruby-on-rails - Rails-在指定时区中选择日期时间

ruby-on-rails - 安装 ruby​​ gems 时无法创建 Makefile

ruby-on-rails - Ruby on Rails 应用程序根目录