ruby-on-railsruby

Why doesn't Rails throw an exception when we access an undefined instance variable in the view?


Suppose we have the following implementation:

app/controllers/cars_controller.rb

class CarsControllers < ApplicationController
  def index
    @test = '7'
  end
end

app/views/cars/index.html.erb

My test variable is <%= @test %>.
Here is an undefined variable <%= @test2 %>.

How come accessing @test2 doesn't throw an exception (Given we are trying to access an instance variable)?


Solution

  • It doesn't pose a problem in your example because @test2 simply returns nil when undefined.

    You can verify this in an irb console session:

    2.6.2 :001 > @test2
     => nil
    

    However ... if you were to call a method assumed to be provided by @test2 then you'd have a problem:

    2.6.2 :002 > @test2.name
    Traceback (most recent call last):
            1: from (irb):2
    NoMethodError (undefined method `name' for nil:NilClass)
    

    In that case, you definitely would receive an error when Rails tried to render the view.