Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do attr_accessor_with_default in ruby?

Tags:

Some code that I had that used attr_accessor_with_default in a rails model is now giving me a deprecation warning, telling me to "Use Ruby instead!"

So, thinking that maybe there was a new bit in ruby 1.9.2 that made attr_accessor handle defaults, I googled it, but I don't see that. I did see a bunch of methods to override attr_accessor to handle defaults though.

Is that what they mean when they tell me to "Use Ruby?" Or am I supposed to write full getters/setters now? Or is there some new way I can't find?

like image 913
Dave Sanders Avatar asked Aug 13 '11 18:08

Dave Sanders


1 Answers

This apidock page suggests to just do it in the initialize method.

class Something
  attr_accessor :pancakes

  def initialize 
    @pancakes = true
    super
  end
end

Don't forget to call super especially when using ActiveRecord or similar.

like image 71
steenslag Avatar answered Oct 22 '22 01:10

steenslag