Are instance variables necessary for Rails as API only?

What role to instance variables play in a Rails API? I am building a backend API in Ruby on Rails and I am following Michael Hartl’s RoR tutorial. He makes use of instance variables in RoR’s templating engine. However, if I am simply using RoR simply as an API, do I still need instance variables?

Below is a snippet from Michael Hartl’s tutorial on how to find a current user.

  def current_user
    if (user_id = session[:user_id])
      @current_user ||= User.find_by(id: user_id)
    elsif (user_id = cookies.signed[:user_id]) # User has closed the browser before and persistent session exists
      user = User.find_by(id: user_id)
      if user&.authenticated?(cookies[:remember_token])
        log_in user
        @current_user = user
      end
    end
  end

I am making web requests from a decoupled frontend, would @current_user always be nil to begin wtih? Can I simply user a regular variable instead?

Answer

If you don’t have any views and the instance variable isn’t used anywhere else in the class (or any classes that inherit from this class), then you can replace them with local variables.

Instance variables are used to either have access to that variable from any instance method within the class, or to expose the variable to a view file.