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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With