0

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.

1
  • Where are you setting @time_opened? I don't think this is the best approach for what you are trying to accomplish but I don't think you are ever setting a value for @time_opened Commented Sep 7, 2016 at 15:07

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You could also use class variables. These are kept between requests but are still not shared between different application server processes. A more common solution is to use a logging system or at least add/update a database record on each visit.
@HolgerJust You could, but you absolutely shouldn't, so it's really not worth mentioning.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.