Rails 5.2 specifying default value for class_attribute

Vishal Telangre

Vishal Telangre

February 21, 2018

This blog is part of our  Rails 5.2 series.

It is very common to set a default value for a class_attribute.

Before Rails 5.2, to specify a default value for a class_attribute, we needed to write like this.

1class ActivityLogger
2class_attribute :logger
3class_attribute :settings
4
5self.logger = Logger.new(STDOUT)
6self.settings = {}
7end

As we can see above, it requires additional keystrokes to set a default value for each class_attribute.

Rails 5.2 has added support for specifying a default value for a class_attribute using default option.

1class ActivityLogger
2class_attribute :logger, default: Logger.new(STDOUT)
3class_attribute :settings, default: {}
4end

This enhancement was introduced in this pull request.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.