BigBinary Blog

We write about Ruby on Rails, React.js, React Native, remote work, open source, engineering and design.

Rails 5.2 specifying default value for class_attribute

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.

class ActivityLogger
class_attribute :logger
class_attribute :settings

self.logger =
self.settings = {}

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.

class ActivityLogger
class_attribute :logger, default:
class_attribute :settings, default: {}

This enhancement was introduced in this pull request.

Vishal Telangre in Rails 5.2
Feb 21, 2018

Subscribe to our newsletter