簡體   English   中英

引導閃存不適用於Rails 4.1.4和simple_form

[英]bootstrap flash doesn't work with rails 4.1.4 and simple_form

我在讓Flashs與bootstrap_flash helper一起使用時遇到困難。 這是我的代碼片段:

application.html.erb

...
<div class="container">
  <%= bootstrap_flash  %>
  <%= yield %> 
</div>
...

bootstrap_flash_helper.rb

ALERT_TYPES = [:error, :info, :success, :warning] unless const_defined?(:ALERT_TYPES)

def bootstrap_flash
  flash_messages = []
  flash.each do |type, message|
    # Skip empty messages, e.g. for devise messages set to nothing in a locale file.
    next if message.blank?

    type = type.to_sym
    type = :success if type.to_s == :notice.to_s
    type = :error   if type.to_s == :alert.to_s
    next unless ALERT_TYPES.include?(type)

    Array(message).each do |msg|
      text = content_tag(:div, content_tag(:button, raw("&times;"), :class => "close", "data-dismiss" => "alert") + msg.html_safe, :class => "alert fade in alert-#{type}")
      flash_messages << text if msg
    end
  end
    flash_messages.join("\n").html_safe
end
end   

我在控制器操作中調用flash [:notice]。

有人可以給我一個提示嗎? 謝謝!

乍一看,您的代碼的最后end太多了。

乍一看,我認為您的代碼中存在一些缺陷:

(1)避免來回投射:

type = type.to_sym
type = :success if type.to_s == :notice.to_s
type = :error   if type.to_s == :alert.to_s

您將type轉換為符號,只是將其轉換回字符串,而將常量符號轉換為字符串以進行比較。 如果省略to_s調用,則無需to_s即可實現相同的目的:

type = type.to_sym
type = :success if type == :notice
type = :error   if type == :alert

(2)使用map而不是helper變量+ each

flash_messages = []
flash.each do |type, message|
  # ...
end
flash_messages.join("\n")

您可以使用Enumerablemapcollect方法創建一個新數組,而不是創建一個臨時變量以將哈希表轉換為數組:

flash.map do |type, message|
  # ...
end.join("\n")

(3)使用映射哈希映射到CSS類:

ALERT_TYPES = {
 :alert => :error, :info => :info, :notice => :success, :warning => :warning
}

通過使用這樣的哈希,您可以簡單地查找匹配項,而不用使用多個if語句來確定正確的類

content_tag(:div, message, class: "alert alert-#{ALERT_TYPES[type.to_sym]}")

總的來說,我認為這將是一個更具可讀性,更簡短和可擴展的解決方案:

ALERT_TYPES = { :alert => :error, :info => :info, :notice => :success, :warning => :warning } unless const_defined?(:ALERT_TYPES)

def bootstrap_flash
  flash.map do |type, message|
    # Skip empty messages, e.g. for devise messages set to nothing in a locale file.
    # This will leave a nil value in the resulting array
    next if message.blank?

    # Skip if it's not a valid alert type
    # This will leave a nil value in the resulting array
    type = type.to_sym
    next unless ALERT_TYPES.keys.include?(type)

    # return the markup for the alert
    content_tag(:div, class: "alert alert-#{ALERT_TYPES[type]} fade in") do
      # use safe_concat() to avoid using html_safe()
      content_tag(:button, raw("&times;"), class: "close", data: { dismiss: "alert" }).safe_concat(message)
    end
  end.join('') # no need to join with \n --> this way nil values will be ignored as well
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM