1

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?:

7
  • What's wrong with the constructor (initialize, invoked on new)? Commented Nov 19, 2014 at 14:21
  • 1
    after_initialize is the way to go Commented Nov 19, 2014 at 14:24
  • 2
    @D-side as it is from AR::Base, you don't want to override initialize as it can break AR.. Commented Nov 19, 2014 at 14:24
  • @Doon got it. And AR provides a replacement the author wants to avoid. Huh. Commented Nov 19, 2014 at 14:25
  • 1
    Be careful that the first @test = 1 has self pointing to your class, not to your instance. Commented Nov 19, 2014 at 14:30

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

issue is you dont update @test in your testing method
This should be @test += 1 if you actually want to modify it.
2

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    

4 Comments

I need use @test in several places.
It's best to use the accessor method than to lean directly on @-style instance variables when writing model code.
@apneadiving Exactly as you have here with the lazy initializer ||=. Once you have that, the @test variable should not be used directly is all I'm saying.
@tadman actually I hesitated but didnt take the time to check :)
1

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

1 Comment

yeah maybe you meant attr_writer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.