Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the proper way to initialize a class_attribute in Rails?

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.

like image 796
poochenza Avatar asked Jan 03 '12 12:01

poochenza


3 Answers

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.

like image 61
lzap Avatar answered Oct 28 '22 06:10

lzap


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
like image 24
user1519240 Avatar answered Oct 28 '22 05:10

user1519240


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
like image 1
sandstrom Avatar answered Oct 28 '22 06:10

sandstrom