Ruby

Ruby

By DeepSource

default value provided to attribute without a block RB-W1014

Anti-pattern
Major
Autofix

Attribute class methods that specify a :default option whose value is an array, string literal or method call should do so by providing a lambda. All other values, such as string, symbol, integer and float literals as well as constants are acceptable as is.

This is so because if you don't provide a lambda, the default value provided will only be executed while the db migration is run and set as a constant value. When you provide a lambda, this default value is dynamic and gets set when you commit save the model to the database.

Bad practice

class User < ApplicationRecord
  attribute :confirmed_at, :datetime, default: Time.zone.now
end

class User < ApplicationRecord
  attribute :roles, :string, array: true, default: []
end

class User < ApplicationRecord
  attribute :configuration, default: {}
end

Recommended

class User < ApplicationRecord
  attribute :confirmed_at, :datetime, default: -> { Time.zone.now }
end

class User < ApplicationRecord
  attribute :roles, :string, array: true, default: -> { [] }
end

class User < ApplicationRecord
  attribute :configuration, default: -> { {} }
end

class User < ApplicationRecord
  attribute :role, :string, default: :customer
end

class User < ApplicationRecord
  attribute :activated, :boolean, default: false
end

class User < ApplicationRecord
  attribute :login_count, :integer, default: 0
end

class User < ApplicationRecord
  FOO = 123
  attribute :custom_attribute, :integer, default: FOO
end

References

  1. ActiveRecord#attribute - APIdock