What is the conditional assignment operator in Ruby on Rails (||=)
Conditional assignment operator is one of those things that you don't need to know as a beginner but you'll see being used commonly in open source code. This article provides a quick intro to it.
Take a look at the method below.
def doorkeeper_token
@doorkeeper_token ||= OAuth::Token.authenticate(
request,
*Doorkeeper.config.access_token_methods,
)
end
OAuth::Token.authenticate
is a computationally expensive method. If they had used the assignment operator '=', it would mean bearing this expense each time doorkeeper_token
was called.
Instead, '||=' assigns a value to @dookeeper_token
only if the variable is falsey. In other words, if the variable does not already store something.
If the variable does store a value, the expression on the right hand side of the operator is not evaluated.
What this means for the above code is that on the first call to the doorkeeper_token
method, the token is authenticated, stored in the instance variable @doorkeeper_token
and returned to the calling method.
But on subsequent calls, the token already stored in @doorkeeper_token
is returned to the calling method without being authenticated again.
There is even a name for this technique - Memoization. Originating from the word "memo". It involves optimising performance by caching the results of expensive method calls and returning the cached results when the method is called again.