rails interview question
I got this question in a previous interview and开发者_如何学Python couldnt do it , any idea? What does this return? Where would it be used?
module ApplicationHelper
def show_flash
flash.map{|key, value| content_tag(:div, value, {:class => key})}
end
end
The 'flash' is a ruby-on-rails convention for storing information generated in one request (say, "invalid username" or "session not found" or "thanks for buying from us" or "cart updated") temporarily for being rendered into the next view from the client.
The flash is a hash-like object.
The .map
method on hash-like objects will iterate over all items in the hash; in this case, the .map
method is being passed a block that accepts two parameters (which it names key
and value
, because the key
could be used to look up the value
from the hash). The block uses the content_tag
helper to output new <div>
elements with the value from the hash and the CSS selector-class key
.
So for a flash like this: {:name => "sars", :food => "pizza"}
It would emit HTML roughly like this: <div class="name">sars</div><div class="food">pizza</div>
.
This is a clever little helper method that probably saves a fair bit of typing, but it makes some assumptions: order in the view doesn't matter, all the keys are either in the CSS already or the CSS is prepared to handle unknown class elements in a graceful way. This helper might only be used once in a template, but it'd still be helpful to have as a method that could be dropped into other projects later.
module ApplicationHelper
def show_flash
flash.map{|key, value| content_tag(:div, value, {:class => key})}
end
end
精彩评论