genghiskhan genghiskhan - 4 months ago 31
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
@time_opened += 1

if @open_time > 0.0
@close_time =

@visit ={number: @number, time_spent: @close_time - @open_time})

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

@open_time =

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.


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.