Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class variable in Rails persisting on browser refresh

I'm pretty new to Ruby and Rails after coming from a long PHP background. I'm getting a weird error thats got me stumped.

I have a class variable set up like so:

class Article < ActiveRecord::Base

    @@customTags = []

    def self.addCustomGA(slot, name, value, scope=3)
        h = {:slot => slot, :name => name, :value => value, :scope => scope}
        @@customTags.push h

    end

    def self.customTagOutput

        tags = ""
        @@customTags.each do |ct|
        tags << "_gaq.push(['_setCustomVar', "+ct[:slot].to_s+", '"+ct[:name].to_s+"', '"+ct[:value].to_s+"', "+ct[:scope].to_s+"]);\n"
        end
        tags
    end

end

I am running a little test in my controller that calls:

Article.addCustomGA(1, 'categories', @article.category_list);

And then in my HAML view I'm outputting the content like so:

#{Article.customTagOutput}

This works great on the first go. But when I refresh the page it keeps adding an entry to the array - so the @@customTags array seems to be persisting across my session! If I don't refresh for a few minutes then it resets itself.

My first thought was some kind of caching thing happening, but Google hasn't turned up anything for me.

like image 788
koosa Avatar asked Dec 07 '25 02:12

koosa


2 Answers

Firstly, don't store anything in a class variable in your model. Class variables are generally a bad idea. This looks like it should really be done in a view helper method in the helpers file for the relevant controller (something like app/helpers/articles_helper.rb).

You shouldn't need to store anything like this for the entire model class. You either store data for each instance, or you hard-code it into the app.

The reason that variable is kept between refreshes is that Rails loads the Article class once (on startup) and the class variable doesn't get re-created (since the class doesn't get reloaded).

like image 51
Alex Coplan Avatar answered Dec 08 '25 15:12

Alex Coplan


Consider simply using an instance variable instead of a class variable, @customTags would only persist only in a single instance of an object of that class and hence if you were to refresh the page an new instance of the object of that class would be created and contain no previous values).

On another note, it's generally considered poor practice to define a variable like this in your model, consider putting in the according helper file.

like image 30
rudolph9 Avatar answered Dec 08 '25 14:12

rudolph9



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!