Getting Format in Mailer View in Rails

断了今生、忘了曾经 提交于 2020-01-06 06:07:07

问题


In my Rails app, I use a method in my Mailer views for creating a link that takes a format param based on whether it's in html or text format.

mailer_link_to( url, link_text, format )

Depending on the format, it either creates an anchor <a> tag for html or just shows the url for text.

So for each Mailer method, I have two views:

myemail.html.erb
myemail.text.erb

In myemail.html.erb, I use mailer_link_to( "http://ntwrkapp.com", "ntwrk", "html" ).

In myemail.text.erb I use mailer_link_to( "http://ntwrkapp.com", "ntwrk", "text" ).

What I'm wondering is if I can determine what the format is so I'm not having to duplicate myself so much and specify "html" or "text" each time.

If I was in a normal view/controller, I would do something like request.format but the request object isn't available in the Mailer views.

Thanks!


回答1:


Use self.formats.

Discovered in this other answer that each view has a .formats method that contains an Array of formats that will get used in partials and whatnot:

self.formats #=> [:text]

So, you can use this to manually pass the current format to the mailer_link_to method like so:

mailer_link_to( "http://ntwrkapp.com", "ntwrk", self.formats.first )

And to preempt anybody saying I should just use a partial, which will automatically pass the correct format, I agree! I simplified my example for the sake of asking the question but in my actual use case I really did need to get the Mailer View's format manually. Thanks for trying to help, tho.



来源:https://stackoverflow.com/questions/47459724/getting-format-in-mailer-view-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!