Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

It has been many times that I have noticed in rails projects programmers using instance variables in model files. I have searched why its used, but couldn't figure out. For the context of things I am reproducing some sample code which looks similar to what I saw.

This is in 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 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 just a local variable insted of instance variable. Would it work fine? It would be helpful if someone could help me out. Thanks.

like image 829
Deepak A Avatar asked Nov 19 '13 11:11

Deepak A


1 Answers

the first time you call method_foo, it wil execute reference.first, save it's value in @method_variable and return it.

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

So if reference.first was a expensive operation, let's say an API call. It would only be executed once for every instance.

like image 163
Reprazent Avatar answered Nov 15 '22 11:11

Reprazent