What is the use of instance variables in the rails model class

There have been many times that I noticed in rails project programmers using instance variables in model files. I was looking for why it was used, but I could not understand. For the context of things, I am reproducing a few code examples that look similar to what I saw.

This is in the controller directory.

class someController < ApplicationController def index @group = Group.find(params[:id]) @group.method_foo # an instance method in model class // some more junk code end end 

This is in the model directory.

 class someModel < ActiveRecord::Base // some relations and others defined def method_foo @method_variable ||= reference.first # I am not so sentimental about what reference.first is, but i want to know what @method_variable is doing there. end end 

What if I use only the local variable instested by the instance variable. Will this work fine? It would be helpful if someone would help me. Thanks.

+6
source share
1 answer

the first time method_foo is called, it will follow the reference.first link, store its value in @method_variable and return it.

The second time, it will simply return the value stored in @method_variable.

So, if reference.first was an expensive operation, say an API call. It will be executed only once for each instance.

+13
source

Source: https://habr.com/ru/post/958391/


All Articles