genghiskhan genghiskhan - 3 months ago 18
Ruby Question

Ruby instance variables nil

I'm attempting to measure the amount of time spent on a page. I am trying to store the opening and closing times in instance variable of the controller; however, they either don't initialize or are nil. Here is my code:

def table
@numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
if @time_opened.nil?
@time_opened = 1
@open_time = 0.0
@close_time = 0.0
else
@time_opened += 1
end

if @open_time > 0.0
@close_time = Time.now
end

@visit = Visit.new({number: @number, time_spent: @close_time - @open_time})
@visit.save
end

def show
url = request.url
@number = url[url.rindex('/')+1..-1]
@title = @number

@open_time = Time.now
end


Show is called every time the page who's time I want to measure is displayed. When I check the visit data, number is nil and time_spent is 0.0.

Answer

You can't share state across requests using instance variables. Your controller instance is completely destroyed at the end of each request, and a new instance of your controller is created the next time a request is routed to one of its actions.

If you want to persist data, you need to either use session or send the data to the client and persist it via <input type="hidden"> fields, so it can be sent back with the subsequent request.