M
M
Mr Freeman2015-07-07 14:38:05
inkscape
Mr Freeman, 2015-07-07 14:38:05

The array grows after page reload, why is this happening?

Hi all. For some reason, the array after .push() is not reset when the page is reloaded. I can't understand why.

class Stats

  class << self
    attr_accessor :condition, :result
  end

  @result = []
  @condition = {}

  def self.get_calculate_stats_by_model(model)
    tracks = Track.all
    # (...)
    tracks.each do |track|
      @result.push(Bar.get_stats_hash(track)
    end

    return @result
  end
end

This model is not from AR - here I just have a separate logic. And every time the page is opened, @result grows, of course I can call @result = [] in each method and I will be happy, but I still don’t understand why this will happen. Yes, and maybe the solution is much better than zeroing the array in each method.
Oh yes, maybe it's because of the controller?
class StatsController < ApplicationController

  before_action :set_default_params

  def campaigns
    @stats = Stats.get_calculate_stats_by_model(Campaign)
    render 'stats'
  end

  private
  def set_default_params
    @condition = {
      :date_from => params[:date_from] || Date.today-7,
      :date_to => params[:date_to] || Date.today,
    }

    Stats.condition = @condition
  end

end

That is, every time the page is reloaded, @result is filled with duplicate records. That is, stupidly, it is not updated, as it would be in PHP. Does the cache for variables somehow work or is my stupidity in logic? Though it on any is present, proceeding from a problem. Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
mikeyuri, 2018-11-01
@Korifa

Select all three objects, then the menu "Contour" / "Sum". Or ctrl++.

J
Jeiwan, 2015-07-07
@vladamir

Because @resultthis is an instanced class variable that lives as long as the Stats class, that is, until the application is restarted, and not until the end of the request processing.
Understanding class instance variables in Ruby

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question