sabaeus sabaeus - 7 months ago 12
Ruby Question

show content to first time visitor of rails app

I want a piece of content to display to first time visitors of a rails app, so I wrote a helper method that checks session and stores a cookie.

My controllers are set up like this:

class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
helper_method :first_time_visiting?

def first_time_visiting?
if session[:first_time].nil?
cookies.permanent[:first_time] = 1
end
end
end

class ItemsController < ApplicationController
before_action :first_time_visiting?
end


And then I'm calling the method in my view like this:

<% if first_time_visiting? %>
<div class="new-visitor-show">Test</div>
<% end %>


I should not be seeing "Test" after first visit, but I am. Am I using the helper method incorrectly?

Answer

You could use this (without helper):

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_action :first_time_visit, unless: -> { cookies[:first_visit] }

  def first_time_visit
     cookies.permanent[:first_visit] = 1
     @first_visit = true
  end
end

The function first_time_visit will be called only once, and so in the view :

<% if @first_visit %>
  <div class="new-visitor-show">Test</div>
<% end %>
Comments