Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

Allow nil for integer settings with nil default value

Christophe Bliard790551c4c876
diff --git a/app/models/setting.rb b/app/models/setting.rb
index ab6b64a12d0..2b86914328c 100644
--- a/app/models/setting.rb
+++ b/app/models/setting.rb
@@ -150,8 +150,22 @@ class Setting < ApplicationRecord
validates :value,
numericality: {
only_integer: true,
- if: Proc.new { |setting| setting.format == :integer }
+ if: ->(setting) { setting.non_null_integer_format? }
}
+ validates :value,
+ numericality: {
+ only_integer: true,
+ allow_nil: true,
+ if: ->(setting) { setting.nullable_integer_format? }
+ }
+
+ def nullable_integer_format?
+ format == :integer && definition.default.nil?
+ end
+
+ def non_null_integer_format?
+ format == :integer && !definition.default.nil?
+ end
def value
self.class.deserialize(name, read_attribute(:value))
diff --git a/spec/models/setting_spec.rb b/spec/models/setting_spec.rb
index be95b643ae4..3f777e4e444 100644
--- a/spec/models/setting_spec.rb
+++ b/spec/models/setting_spec.rb
@@ -179,6 +179,47 @@ describe Setting, type: :model do
expect { described_class.smtp_openssl_verify_mode = 'none' }
.to raise_error NoMethodError
end
+
+ context 'for a integer setting with non-nil default value', :settings_reset do
+ before do
+ Settings::Definition.add(
+ 'my_setting',
+ format: :integer,
+ default: 42
+ )
+ end
+
+ it 'does not save it when set to nil' do
+ expect(described_class.my_setting).to eq(42)
+ described_class.my_setting = nil
+ expect(described_class.my_setting).not_to be_nil
+ expect(described_class.my_setting).to eq(42)
+ end
+ end
+
+ context 'for a integer setting with nil default value', :settings_reset do
+ before do
+ Settings::Definition.add(
+ 'my_setting',
+ format: :integer,
+ default: nil
+ )
+ end
+
+ it 'saves it when set to nil' do
+ described_class.my_setting = 42
+ expect(described_class.my_setting).to eq(42)
+ described_class.my_setting = nil
+ expect(described_class.my_setting).to be_nil
+ end
+
+ it 'saves it as nil when set to empty string' do
+ described_class.my_setting = 42
+ expect(described_class.my_setting).to eq(42)
+ described_class.my_setting = ''
+ expect(described_class.my_setting).to be_nil
+ end
+ end
end
describe '.[setting]_writable?' do