gates gates - 11 months ago 47
Ruby Question

How the replacement of auth_token field is working in below scenario

class User < ActiveRecord::Base
def facebook
@facebook ||=

In the rails console

user = User.first

First question is, User model has a column called oauth_token, which is magically getting replaced in
here, even though I am not passing oauth_token explicitly

Second question, what is the need of caching @facebook variable here? I am following this rails casts tutorial


@First question

What do you mean by getting replaced? From what I see when initializing API ( you are passing ouath_token that is assigned to specific user. When calling User.first you're loading first user from database, and ActiveRecord automatically assigns oauth_token to newly created instance. If ouath_token was never saved (thus present in db record) it would be nil.

@Second question

This is in general done for performance reasons in order to avoid multiple API calls within same request. However, usually response from API call is cached not the API instance itself. Maybe that Koala API instance calls webservice directly in constructor (in its initialize method).

My note - keeping such methods like facebook calling external webservice within User model ends with very difficult to change code. It's better to move it somewhere out from this model.