views:

176

answers:

4

I know Rails' flash hash is nothing new, but I keep running into the same problem with it.

Controllers should be for business logic and db queries, not formatting strings for display to the user. But the flash hash is always set in the controller. This means that I need to hack and work around Rails to use Helpers that I made to format strings for the flash hash.

Is this just a pragmatic compromise to MVC or am I missing something here?

How do you deal with this problem? Or do you not even see it as one?

+1  A: 

It appears to be possible to "forcefully" access helpers from controllers. See this discussion here:

http://lojic.com/blog/2007/07/27/using-helpers-inside-controllers-in-ruby-on-rails/

You could also "render" a partial to an instance variable. See this page:

http://snippets.dzone.com/posts/show/396

Normally, if you call "render_partial" within a controller, nothing but the partial will be rendered.

Occasionally, it is useful to render a partial to an instance variable as a string so that the view can still be rendered as normal, and the string can be passed in to the view.

add_variables_to_assigns

@content_for_navbar = @template.render_partial 'layouts/public_navbar'`

shedd
+1  A: 

Rails isn't necessarily strictly MVC. In the Rails world, controllers are more like what would otherwise be called View-Controllers in the MVC pattern.

Also, I would argue that in 'pure' MVC, the controllers should not be doing DB queries and business logic—that should be encapsulated in the model layer. Controllers are about moving data between the view and the model.

What about creating helper methods for the view that format whatever you stick into the flash hash? The flash needn't only contain string values; it can contain arbitrary objects. I often find myself putting an array of model validation errors into flash[:error], and writing a helper method to format those messages into a <ul>.

Kevin
A: 

If you'd really like to, you can store a key in the flash variable and then in the view translate that key into an actual message. How the flash displays isn't in any way built-in. It all depends on how much work you are willing to put into it in order to get pure MVC.

Matchu
A: 

The method described by shedd didn’t work for me. The second method described in http://snippets.dzone.com/posts/show/396 did work:

@content_for_navbar = render_to_string :partial => "layouts/public_navbar"
tow8ie