Why isnt my simple counter working?

Hello,

Im on chapter 8 of the agile book and I cant get this simple counter to
work.
Its suppose to count how many times a person visited the home page and
display it when its more than 5.

store_controller.rb:

def index
@count = increment_count
end

def increment_count
if session[:counter].nil?
session[:counter] = 0
end
session[:counter] += 1
end

store.rhtml:
<% if @count > 5 %>
<%= @count %> visits
<% end %>

This works when I just refresh the page on the home page, but when I
click on the “add to cart” button which envokes the add_to_cart method
and directs to the add_to_cart view, then it gives me an error that
@count is nil.

NoMethodError in Store#add_to_cart

Showing app/views/layouts/store.rhtml where line #21 raised:

You have a nil object when you didn’t expect it!
The error occurred while evaluating nil.>

Why does @count suddenly become nil when it has value before?

Thanks in advance!

On 2/8/07, Kristen [email protected] wrote:

NoMethodError in Store#add_to_cart

Showing app/views/layouts/store.rhtml where line #21 raised:

You have a nil object when you didn’t expect it!
The error occurred while evaluating nil.>

Why does @count suddenly become nil when it has value before?

Thanks in advance!

You’ve set the @count variable in the index method. Is it set in your
add_to_cart method as well? Perhaps you could extract that into a
before_filter to set @count for you. Something like this may get you
started

before_fitler :set_visits

def index
increment_count
set_visits
end

private

def increment_count
session[:counter] ||= 0
session[:counter] += 1
end

def set_visits
@count = session[:counter]
end

before_fitler :set_visits

def index
increment_count
set_visits
end

private

def increment_count
session[:counter] ||= 0
session[:counter] += 1
end

def set_visits
@count = session[:counter]
end

thanks for the tip. Ill have to take a look at the filters since i dont
knwo anything about them yet.