Welcome to Working With Rails

 

Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
static variables works differently in two different envs
5 Posts
static variables works differently in two different envs

One issue you may run into with using static variables is that they are specific to each Ruby thread (v1.8). If you fire up multiple threads in a production environment, they will not share static state.

A much better solution is to use either a persistent store or a shared cache store, depending on what you're trying to do.

You can change this behavior in the development environment by changing the value of config.cache_classes in config/environments/development.rb. Set the value to true and Rails will no longer perform the class reloading; which means you'll have to restart your server for each change you make.

However, I would thoroughly consider finding a solution to your problem which does not involve a class variable. Chances are very good that you can write the same functionality without one. Chances are also very good that doing so will make your code cleaner, and you get the added benefit of not having the problem with class reloading.

good explanation.... but with this behavoiur really confuses develoments specially with the static or global variables. As we know static concept is very much useful in day to day development.. So in order to deal with them we have to do the developments either test or production envs, not with the development. I think that's a bit hazzzel.

By default, Rails reloads your classes on every request in the development environment; it does not do this in the test environment. So, on each request in development Rails throws out your Movie class definition and reparses the code, resetting the class variable.

Rails performs class reloading in development so you needn't restart the server each time you make a change, but it doesn't lead to some confusing behaviors now and then.

example code is as follows,

class Movie @@name = [] def self.name

@@name

end end

class MoviesController < ApplicationController

def index
  Movie.name.push "x"
  render :text=>"#{Movie.name.length}"
end

end

Here is the issue : if we run the project in dev environment, every time when i invoke index method in movies_controller it displays same value as 1. Which means static variable gets reset request by request.But this behavior changes when i run it in test env. Then the display gets increased in each requests. eg:-1,2,3.... This means static variable does not get reset for the each request.

Any explanations for this different behaviors ?

5 Posts
Login to add your message