9

I have a lot action methods which do not need to create instance variable for rendering the view, because these method will only redirect to other actions from other controllers. I am wondering: is it a good habit to always create instance variable for the sake of following the conventions of Rails, or there is no such thing. My intuition is that local variable reduces memory costs, but the code does not look pretty.

3 Answers 3

12

It's not a convention to create instance variables if they're not being sent to the view.

  • Variables should have the narrowest scope possible.
  • They should be locals if they're not passed to the view.
  • Use a presenter if you have a "lot" of view data (instead of a ton of instance vars).

Instance variables may be used if multiple methods act on them before the view, even if they're not used in the view, but this makes the code much harder to reason about and test in isolation.

If you find yourself using instance variables to hold intermediate calculations you probably need to rethink your flow and/or design.

Sign up to request clarification or add additional context in comments.

1 Comment

Also, using instance vars where local vars would do, holds onto the memory reference longer than is necessary. To stay lean is beneficial for a variety of reasons.
8

Mostly we need to use instance variable in following cases,

  1. When we need to access the variable from view
  2. If we are calling a method from the action, instead of returning a value, we can directly update the variable from the called method.

Why should we use instance variable if our job can be done with a local variable.

1 Comment

One more case we can make use of instance variable is with use of caching, example - def total_budget @totoal_budget ||= calculation goes here end
5

The only reason you use instance variables in controllers is get things into the view without having to explicitly pass a pile of state around.

If you don't have any state, then you don't have any instance variables so there's no reason to use them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.