diff options
author | GitLab Bot <gitlab-bot@gitlab.com> | 2021-02-18 13:34:06 +0300 |
---|---|---|
committer | GitLab Bot <gitlab-bot@gitlab.com> | 2021-02-18 13:34:06 +0300 |
commit | 859a6fb938bb9ee2a317c46dfa4fcc1af49608f0 (patch) | |
tree | d7f2700abe6b4ffcb2dcfc80631b2d87d0609239 /app/models/concerns/nullify_if_blank.rb | |
parent | 446d496a6d000c73a304be52587cd9bbc7493136 (diff) |
Add latest changes from gitlab-org/gitlab@13-9-stable-eev13.9.0-rc42
Diffstat (limited to 'app/models/concerns/nullify_if_blank.rb')
-rw-r--r-- | app/models/concerns/nullify_if_blank.rb | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/app/models/concerns/nullify_if_blank.rb b/app/models/concerns/nullify_if_blank.rb new file mode 100644 index 00000000000..5a5cc51509b --- /dev/null +++ b/app/models/concerns/nullify_if_blank.rb @@ -0,0 +1,48 @@ +# frozen_string_literal: true + +# Helper that sets attributes to nil prior to validation if they +# are blank (are false, empty or contain only whitespace), to avoid +# unnecessarily persisting empty strings. +# +# Model usage: +# +# class User < ApplicationRecord +# include NullifyIfBlank +# +# nullify_if_blank :name, :email +# end +# +# +# Test usage: +# +# RSpec.describe User do +# it { is_expected.to nullify_if_blank(:name) } +# it { is_expected.to nullify_if_blank(:email) } +# end +# +module NullifyIfBlank + extend ActiveSupport::Concern + + class_methods do + def nullify_if_blank(*attributes) + self.attributes_to_nullify += attributes + end + end + + included do + class_attribute :attributes_to_nullify, + instance_accessor: false, + instance_predicate: false, + default: Set.new + + before_validation :nullify_blank_attributes + end + + private + + def nullify_blank_attributes + self.class.attributes_to_nullify.each do |attribute| + assign_attributes(attribute => nil) if read_attribute(attribute).blank? + end + end +end |