0

I am not quite clear on the life cycle of instance variables in Ruby on Rails.

  1. I have an instance variable @work_days (into which I fetch and load the list of all working days in a month. The month is selected by the user from a date_select in the UI).

  2. Now I have a Generate Report button which generates an excel report by calling a show method in the controller

  3. Every time the user clicks the Generate Report button (and show method gets called), the value of @work_days seems to be nil and I have to initialize it every time.

Is there a way to avoid this? Why does the value of instance variable become nil every time the controller's method show is called?

mrzasa
  • 22,895
  • 11
  • 56
  • 94
Biju
  • 820
  • 1
  • 11
  • 34

1 Answers1

1

Rails controller is instantiated per request. It means that every time you receive a request all instance variables are nil and you need to initialize them.

mrzasa
  • 22,895
  • 11
  • 56
  • 94
  • thanks much for the clarification. Is the same true for class variables as well? – Biju Dec 07 '18 at 14:09
  • It depends where you set them. In general, they live as long as the class lives (unless they're unset explicitly). – mrzasa Dec 07 '18 at 14:10
  • will the controller class live across multiple requests? – Biju Dec 07 '18 at 14:20
  • 1
    yup. it's loaded once and then lives in memory. – mrzasa Dec 07 '18 at 14:22
  • I would like to check if a `function` inside a controller is being called for the very first time in the user's session. Is a `class variable` the right choice for this? Any good practice as to how to implement this check? – Biju Dec 07 '18 at 14:24
  • If you want to check it it in the session scope. use the session. I think it's a topic for another question :) – mrzasa Dec 07 '18 at 14:27
  • Thanks much @mrzasa - I have posted https://stackoverflow.com/questions/53673142/how-to-track-the-very-first-time-a-controller-is-called-in-a-user-session-ruby for this – Biju Dec 07 '18 at 16:11
  • Just one question please. You said the controller class is loaded once and lives in memory (unless explicitly ended). You also mentioned a controller instance is created for every request. When all the requests end, won't the controller class be unloaded as well? Say a user opens an application session and makes 5 requests to one particular controller. All 5 requests have completed but the user is still logged in to the app. But since all controller requests (and hence instances as well) have ended, won't the class be unloaded? Or will the class stay loaded even though it has only 0 instances? – Biju Dec 07 '18 at 16:14
  • I don't think so. Class is loaded when app starts or when it's used for the first time (depending on configuration) and then lives in memory. – mrzasa Dec 07 '18 at 16:17