Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize 'attr_accessor' attribute values? [duplicate]

Possible Duplicate:
attr_accessor default values

I am using Ruby on Rails 3.0.9 and I would like to initialize some attr_accessor attribute values in my class\model that inherits from ActiveRecord::Base. That is,

... in my module I have:

class User < ActiveRecord::Base
  attr_accessor :attribute_name1,
                :attribute_name2,
                :attribute_name3,
                ...
end

and I would like to set to true all attr_accessor attribute values. How can I do that?

P.S.: Of course I would like to solve the above issue approaching "à la Ruby on Rails Way". I know about the after_initialize callback but by using that method I should repeat each attribute_name<N> statement for which I would like to set the value to true inside that after_initialize statement (... and this is not DRY - Don't Repeat Yourself). Maybe there is a better way to achieve this. Is there a way to set attr_accessor attribute values "on the fly" when you state those attributes? That is, I expect to declare and set attr_accessor attributes at once!

like image 292
Backo Avatar asked Aug 16 '11 16:08

Backo


2 Answers

For Rails 3.2 or earlier, you could use attr_accessor_with_default:

class User < ActiveRecord::Base
  attr_accessor_with_default :attribute_name1, true
  attr_accessor_with_default :attribute_name2, true
  attr_accessor_with_default :attribute_name3, true
  ...
end

Since your default value is an immutable type (boolean), this form of the method is safe to use here. But don't use it if the default value is a mutable object, including an array or string, because all of your new model objects will share the exact same instance, which is probably not what you want.

Instead, attr_accessor_with_default will accept a block, where you can return a new instance each time:

attr_accessor_with_default(:attribute_name) { FizzBuzz.new }
like image 104
Steve Avatar answered Oct 31 '22 14:10

Steve


Did you try:

class User < ActiveRecord::Base
  attr_accessor :attribute_name1,
                :attribute_name2,
                :attribute_name3,
                ...

  after_initialize :set_attr

  def set_attr
    @attribute_name1 = true
    ...
  end
end
like image 31
apneadiving Avatar answered Oct 31 '22 13:10

apneadiving