Luiz Carvalho
Luiz Carvalho

Reputation: 1419

Best Way to initialize a instance variable in Rails

I'm having trouble initializing instance variables in Rails, need to use a variable in different methods, but this needs to be initialized beforehand, eg:

class Test < ActiveRecord::Base    
  @test = 1

  def testing
    @test+1
  end    
end

t = Test.new
t.testing

I get the follow error:

test.rb:4:in `testar': undefined method `+' for nil:NilClass (NoMethodError)
    from test.rb:9:in `<main>'

Is there a more elegant way to initialize a variable without using the after_initialize?:

Upvotes: 1

Views: 1465

Answers (3)

Luiz Carvalho
Luiz Carvalho

Reputation: 1419

So after_initialize seems to be really the best solution.

class Test < ActiveRecord::Base

  after_initialize do
    @test = 1
  end

  def testing
    @test+=1
  end
end

Upvotes: 3

apneadiving
apneadiving

Reputation: 115541

If you really dont want to use after_initialize, create the variable on the fly:

attr_writer :test

def testing
  self.test += 1
end

def test
  @test ||= 0
end    

Upvotes: 2

eugen
eugen

Reputation: 9226

What you've defined in your code is a @test class instance variables, and you probably wanted just an instance variable. Using after_initialize is overkill here, you can do something like:

  def test
    @test ||= 1
  end

Upvotes: 1

Related Questions