What approach do you take for embedding links in flash messages?

后端 未结 3 1002
夕颜
夕颜 2020-12-24 13:29

The ability to have flash messages (notice, error, warning, etc) with embedded links is nice from a user interaction standpoint. However, embedding an anchor tag inside a f

3条回答
  •  再見小時候
    2020-12-24 13:54

    Glenn Gillen has an approach that he calls Useful Flash Messages in Rails.

    I modified his code snippets to be a little more idiomatic (for me at least).

    The controller fills the flash like this:

    flash[:notice]      = "Your profile was updated. %s"
    flash[:notice_item] = ["Edit again?", edit_profile_path(@profile)]
    

    You then might have helpers that look something like this:

    def render_flash_messages(*keys)
      messages = keys.collect do |key|
        content_tag(:p, flash_message_with_item(key), :class => "flash #{key}") if flash[key]
      end.join
      content_tag(:div, messages, :id => "flash_messages") unless messages.blank?
    end
    
    def flash_message_with_item(key)
      item = flash["#{key}_item".to_sym]
      substitution = item.is_a?(Array) ? link_to(*item) : item
      flash[key] % substitution
    end
    

    The view looks simply like this:

    <%= render_flash_messages(:error, :notice, :warning) %>
    

    The view (via the flash_message_with_item helper) is responsible for creating the anchor tag, but the controller manages what goes into the flash message including an optional resource for further action.

提交回复
热议问题