Task C: Cart Creation #1

Dave says:

I'd put a method in my controller to increment the counter. It might look something like

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

However, a more idiomatic way in Ruby is to do

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

(Yes, it can be done in one line, using a semi-colon as a delimiter, but I think the above is clearer)

Then, I'd set an instance variable to this value in each of the actions I wanted to count

def index
  # ...
  @count = increment_count
end

Mark says:

that would sum all the counted actions though, wouldn't it - as the session :count variable can't differentiate between actions. so if you'd viewed the index action 3 times and the add_to_cart action twice, the count would show as 5.

Chas says:

No Mark, it wouldn't. Dave has placed the call to increment_count inside the index action and not the add_to_cart action, the result is increment_count is only called when the index action has been called.

page_revision: 0, last_edited: 1196813103|%e %b %Y, %H:%M %Z (%O ago)
Unless stated otherwise Content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License