diff options
author | Sean McGivern <sean@mcgivern.me.uk> | 2018-06-11 12:51:36 +0300 |
---|---|---|
committer | Sean McGivern <sean@mcgivern.me.uk> | 2018-06-11 12:51:36 +0300 |
commit | a4f37e1834dbd755981b0ce19617e99b4ea43bb7 (patch) | |
tree | 25eafcc09da9a7d1fea4a22e5e531ddb523379ce /app/models/concerns | |
parent | a239936a4d16836670399952b91a18e1b2a35dc9 (diff) | |
parent | 0665a8f730e19e180f2b4d240ca7e93408d61b12 (diff) |
Merge branch 'rails5-enum-nil' into 'master'
Enable mapping to nil in enums
Closes #47032 and #46279
See merge request gitlab-org/gitlab-ce!19288
Diffstat (limited to 'app/models/concerns')
-rw-r--r-- | app/models/concerns/enum_with_nil.rb | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/app/models/concerns/enum_with_nil.rb b/app/models/concerns/enum_with_nil.rb new file mode 100644 index 00000000000..6b37903da20 --- /dev/null +++ b/app/models/concerns/enum_with_nil.rb @@ -0,0 +1,33 @@ +module EnumWithNil + extend ActiveSupport::Concern + + included do + def self.enum_with_nil(definitions) + # use original `enum` to auto-define all methods + enum(definitions) + + # override auto-defined methods only for the + # key which uses nil value + definitions.each do |name, values| + next unless key_with_nil = values.key(nil) + + # E.g. for enum_with_nil failure_reason: { unknown_failure: nil } + # this overrides auto-generated method `unknown_failure?` + define_method("#{key_with_nil}?") do + Gitlab.rails5? ? self[name].nil? : super() + end + + # E.g. for enum_with_nil failure_reason: { unknown_failure: nil } + # this overrides auto-generated method `failure_reason` + define_method(name) do + orig = super() + + return orig unless Gitlab.rails5? + return orig unless orig.nil? + + self.class.public_send(name.to_s.pluralize).key(nil) # rubocop:disable GitlabSecurity/PublicSend + end + end + end + end +end |