A clean approach to developing notifications / warnings when materializing toast

I use devise in my rails application, and as a standard, it comes with methods noticeand alertthat are visualized on certain actions (for example, when a user logs in).

I also use Materialize CSS and they provide a nice clean Toast style Notification . This is the first approach when working with noticeand alertwith Toast.

<% if notice %>
  <script type="text/javascript">
    Materialize.toast('<%= notice %>', 4000)
  </script>
<% end %>
<% if alert %>
  <script type="text/javascript">
    Materialize.toast('<%= alert %>', 4000)
  </script>
<% end %>

Can someone provide a cleaner / more DRY solution? Feels a bit hacked.

+4
source share
4

"" , DRYer:

<% flash.each do |message_type, message| %>
    <%= javascript_tag "Materialize.toast('#{message}', 4000)" %>
<% end %>
+8

, "". :

<% flash.each do |type, message| %>
  <% if type == "success" %>
    <div class="alert alert-success alert-dismissable" role="alert">
      <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
      <i class="icon-check"></i>
      <p><%= message.html_safe %></p>
    </div>
  <% elsif type == "toast" %>
    <script>
      $(function() {
        Materialize.toast("<%= message %>", 3000);
      });
    </script>
  <% else %>
    <div class="alert alert-danger alert-dismissible" role="alert">
      <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
      <i class="icon-notice"></i>
      <%= message.html_safe %>
    </div>
  <% end %>
<% end %>

, .

, , flash- js, ( , - , ).

+3

. - .

<% unless flash.empty? %>
    <script>
      <% flash.each do |f| %>
      <% type=f[0].to_s.gsub('alert', 'red').gsub('warning', 'orange').gsub('success', 'green') %>
      Materialize.toast('<%= f[1] %>', 4000, '<%= type %>')
      <% end %>
    </script>
<% end %>
+1

Source: https://habr.com/ru/post/1628390/


All Articles