Home > other >  How to run cookie only once
How to run cookie only once

Time:05-26

I have a script that I only want to run the first time the user goes to the new_profile view, so I want to save a cookie and then check if there's the cookie, if not, run the script, if yes don't run the script

I have a controller like this:

    def sign_up()
     cookies.permanent[:is_first_time] ||= true
     redirect_to new_profile
    end

And in my view I have:

<% if cookies[:is_first_time] %>
  <script>
    console.log("script loaded");
  </script>
<% end %>

Is there an option to have something like this:

<% if cookies[:is_first_time] = true %>
  <script>
    console.log("script loaded");
    cookies[:is_first_time] == false;
  </script>
<% end %>

CodePudding user response:

I am not entirely sure if I understand what you want to do but from the example code I would guess that you actually want to do this:

<% if cookies[:is_first_time] %>
  <script>
    console.log("script loaded");
    <% cookies[:is_first_time] = false %>
  </script>
<% end %>

CodePudding user response:

I would suggest different naming

<% unless cookies[:script_was_loaded] %>
  <script>
    console.log("script loaded");
    <% cookies[:script_was_loaded] = true %>
  </script>
<% end %>
  • Related