What's the proper way to initialize a class_attribute
in Rails?
I am using this:
class Foo < ActiveRecord::Base
class_attribute :foobar
self.foobar = []
# ...
end
Which seems to work fine, but also seems to look a bit non-Railsy to me.
Everything is described here: http://apidock.com/rails/Class/class_attribute
If you click on "Show source" you will see there are no options available to set default value. You are doing it right.
A default
option was added on branch master of Rails this year, check: https://github.com/rails/rails/pull/29270. With this change, you can do:
class Foo < ActiveRecord::Base
class_attribute :foobar, default: []
end
What you've done works well (unless you are inheriting).
If you are inheriting from this class you can use the inherited
method to avoid 'leaking'.
def self.inherited(sub_class)
self.foobar = self.foobar.clone
# or `self.foobar = []`
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With