diff options
author | Jan Provaznik <jprovaznik@gitlab.com> | 2018-05-31 21:32:36 +0300 |
---|---|---|
committer | Jan Provaznik <jprovaznik@gitlab.com> | 2018-06-06 21:46:54 +0300 |
commit | 0665a8f730e19e180f2b4d240ca7e93408d61b12 (patch) | |
tree | daaaecc755f15629c9e28eeaeb0e15dd2a6654ec /app/models/concerns/enum_with_nil.rb | |
parent | 41eab9a90787162ee338fd2e3a81827a9bc923c3 (diff) |
Enable mapping to nil in enums
Enum in Rails 5 does not map nil values - IOW nil value remains nil,
even if there is a key with nil value in the enum definition.
This commit overrides the underlying Enum methods so nil value is
still mapped. This solution is far from being ideal: it uses dynamic
definition of methods which introduces more magic/confusion
into the codebase.
It would be better to get rid of the nil value in enums.
Diffstat (limited to 'app/models/concerns/enum_with_nil.rb')
-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 |