Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clean approach to devise notice/alerts in materialize toast

I'm using devise in my rails app and as standard it comes with notice and alert methods which render on specific actions (e.g. a user signing in).

I am also using the Materialize CSS framework and they provide a nice clean 'Toast' style notification. This is the first approach at making notice and alert work with 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 anyone provide a cleaner/more DRY solution? Feels a little hacky.

like image 471
MikeHolford Avatar asked Feb 11 '16 21:02

MikeHolford


2 Answers

It mast be not the "hackyest" way, but still a bit DRYer:

<% flash.each do |message_type, message| %>
    <%= javascript_tag "Materialize.toast('#{message}', 4000)" %>
<% end %>
like image 121
Vlad Avatar answered Oct 22 '22 07:10

Vlad


I don't think I'd necessarily consider that technique 'hacky'. This works well for me in my production app:

<% 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 %>

Just my opinion here, but I don't see anything wrong with that.

Bottom line is I don't think there is a way out of the box to have your flash trigger js other than doing it this way (but I'm all ears if someone thinks they have a better solution).

like image 3
Greg Blass Avatar answered Oct 22 '22 06:10

Greg Blass