patternrubyrailsMinor
HTML flash messages
Viewed 0 times
flashmessageshtml
Problem
Flash messages are generally composed in the controller. Sometimes we need those flash messages to have links in them (like an undo button).
How would you compose such a message?
The only sane way I have found to create such messages is by a presenter that includes much of ActionView in it (in order to gain access to most of the view helpers).
Right now the code in the controller looks like this:
and in the view I do a `` to display it.
How would you compose such a message?
The only sane way I have found to create such messages is by a presenter that includes much of ActionView in it (in order to gain access to most of the view helpers).
Right now the code in the controller looks like this:
def publish
@post.publish!
flash[:notice] = "Post #{@post.title} " +
"was published successfully"
redirect_to @post
endand in the view I do a `` to display it.
Solution
You actually have several options. One way to clean this up a bit would be to use Rails' I18n module, e.g.:
Then in your controller:
And the view:
(You could also do this the other way around and just put "
An alternative is to break what you need out into a partial, e.g.
And then in your controller:
Finally, you could do it in a helper instead:
Then in the controller:
And the view:
Which one you should use is sort of a toss-up to me. I'm fond of the I18n approach but partly because I prefer to keep messages like this in locales anyway. Use whatever makes the most sense to you.
# config/locales/en.yml
en:
post_successful_html: Post %{title} was
published successfully.
# the _html suffix marks the string as HTML-safe automatically
Then in your controller:
flash[:notice] = t :post_successful_html, :url => post_path( @post ),
:title => @post.title
And the view:
(You could also do this the other way around and just put "
:post_successful_html" in flash and then call t flash[:notice], :url => ... in the view but that feels messier to me.) Using I18n for just one thing seems a little like overkill but it is nice and clean (and if you've ever considered localizing your your app it's never too early to start).An alternative is to break what you need out into a partial, e.g.
_post_successful_flash.html.erb:Post was published successfully.
And then in your controller:
flash[:notice] = render_to_string :partial => 'post_successful_flash',
:object => @post, :as => :post
Finally, you could do it in a helper instead:
module PostsHelper
def render_post_successful post
"Post #{link_to post.title, post} was published successfully."
end
end
Then in the controller:
flash[:notice] = :post_successful
And the view:
Which one you should use is sort of a toss-up to me. I'm fond of the I18n approach but partly because I prefer to keep messages like this in locales anyway. Use whatever makes the most sense to you.
Context
StackExchange Code Review Q#9629, answer score: 2
Revisions (0)
No revisions yet.