我在 /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_words
和 ActionView::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
这就是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
关于ruby-on-rails - 从/lib 目录中定义的类访问 ActionView::Helpers::DateHelper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41864046/