二、rails的flash&bootstrap的封装

2019-05-14  本文已影响0人  求墨者

Step 1. 导入库

app/assets/javascripts/application.js

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap/alert
//= require_tree .

Step 2. flashes_helper的逻辑层封装

app/helpers/flashes_helper.rb

module FlashesHelper
  # 常量哈希对象
  FLASH_CLASSES = { alert: "danger", notice: "success", warning: "warning"}.freeze

  # 传一个键进去,提取FLASH_CLASSES对象的值
  def flash_class(key)
    # 第一个参数 key.to_sym 是字符串 转换为 符号
    # 第二个参数 key 就是如果没有查询到值,就用它作为默认值
    FLASH_CLASSES.fetch key.to_sym, key
  end
  
  # 获取筛选后的flash的哈希对象
  def user_facing_flashes
    # flash 的一个内部对象
    # to_hash 是一个将对象转为哈希的方法
    # slice 是一个切片保留的方法,保留哈希中键为后面值的方法
    flash.to_hash.slice "alert", "notice","warning" 
  end
end

Step 3. _flashes的视图层封装

app/views/common/_flashes.html.erb

<%# 判断flash对象是否有传递参数 %>
<% if flash.any? %>
  <%# 同时传多个 %>
  <% user_facing_flashes.each do |key, value| %>
    <%# 获取值 %>
    <div class="alert alert-dismissable alert-<%= flash_class(key) %>">
      <button class="close" data-dismiss="alert">×</button>
      <%= value %>
    </div>
  <% end %>
<% end %>

Step 4. 嵌入

app/views/layouts/application.html.erb

<%= render "common/flashes" %>
<%= yield %>

Step 5. 测试

app/controllers/welcome_controller.rb

class WelcomeController < ApplicationController
  def index
    flash[:notice] = '早安!你好!'
    flash[:warning] = '午安!保持微笑!'
    flash[:alert] = '晚安!该睡了!'
  end
end

Step 6. git存档

$ git add .
$ git commit -m "add bootstrap flash function"

参考资料

liyuanlacfo-blog

上一篇下一篇

猜你喜欢

热点阅读