[英]Rails - can't figure out where to put a very simple string-formatting helper method
解决了。 见注2和3。
我想我只是不理解Rails 3 + ruby 1.9.2中的类...
我们将actionmailer与delayjob结合使用。 一切正常,除了我只是尝试添加一些电话号码,并且尝试添加一个简单的方法pretty_phone(格式化电话号码),该方法不会引发错误:
Class#sample_email failed with NoMethodError: undefined method `pretty_phone'
我已经在model_helper.rb,application_helper.rb和类中尝试过,我猜是我们的电子邮件模型foo_mailer.rb(FooMailer <ActionMailer :: Base)
我们的项目设置是这样的:
app
controllers
widgets_controller.rb
helpers
application_helper.rb
widgets_helper.rb
mailer
foo_mailer.rb ***
models
widget.rb
views
widget
(usual edit,show, etc views)
foo_mailer
sample_email.html.haml ***
这是我尝试添加的简单方法:
# num is a string, always in format 12223334444 we want (222)333-4444
def pretty_phone(num)
return "(" + num[1,3] + ")" + num[4,3] + "-" + num[7,4]
end
foo_mailer.rb非常简单:
class FooMailer < ActionMailer::Base
helper :application **** THIS ALMOST MAKES IT WORK SEE NOTE 2
include ApplicationHelper **** AND THIS ALSO IS REQUIRED NOTE 3
default :from => "Support <support@mydomain.com>"
def sample_email(thewidget)
@widget = thewidget
send_to = @widget.contact_email
if !send_to.blank?
mail :to => send_to,
:subject => "alert regarding #{pretty_phone(@widget.userphone)}"
end
end
end
在查看电子邮件的过程中,我们还使用#{pretty_phone(@widget.userphone)}
我真的很想理解为什么我不能将那个帮助程序放在application_helper甚至foo_mailer.rb中并使它工作-以及它应该去哪里?
(当前,我在application_help.rb中有帮助程序,我们所有的小部件erb视图都可以正常使用它……只是电子邮件视图和/或类文件foo_mailer.rb引发了错误。)
笔记2
通过在foo_mailer.rb的顶部添加helper :application
,现在application_help.rb中的pretty_phone()helper方法可在foo_mailer视图中使用,但不适用于foo_mailer.rb本身。 因此,例如,我想在电子邮件的主题行中使用pretty_phone()时,它将不起作用。 但是在实际的电子邮件(视图)中它确实起作用。
在我看来,这很奇怪-有什么建议吗?
注3:需要添加“ include”和“ helper”。
我在哪里将辅助方法用于ActionMailer视图? 我认为这正是您所需要的。
答案是问题的一部分。 感谢所有提出最终解决方案的人。 我试图将这个问题“标记”为已回答,所以人们不会觉得他们需要提供另一个答案,但是有人删除了我之前的答案。 因此,我将其再次添加回去,这样一两天后系统就会让我将此问题标记为已回答。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.