我在使用bootstrap_flash帮助程序进行闪烁时遇到了困难。 这是我的代码片段:
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("×"), :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]。
有人可以给我一个暗示吗? 谢谢!
答案 0 :(得分:0)
乍一看,代码中的最后一个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
次调用,则可以实现相同的操作而无需强制转换:
type = type.to_sym
type = :success if type == :notice
type = :error if type == :alert
(2)使用map
代替辅助变量+ each
:
flash_messages = []
flash.each do |type, message|
# ...
end
flash_messages.join("\n")
您可以使用Enumerable
的{{3}}或map
方法创建新数组,而不是创建临时变量来将哈希转换为数组:
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("×"), 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