简体   繁体   English

Ruby实例变量nil

[英]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. 但是,它们要么不初始化,要么为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. 每当我要测量的时间页面显示时,都会调用Show。 When I check the visit data, number is nil and time_spent is 0.0. 当我检查访问数据时,数字为nil,time_spent为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. 如果要保留数据,则需要使用session或将数据发送到客户端,然后通过<input type="hidden">字段保留数据,以便可以将其与后续请求一起发送回去。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM