Add grouping feature to SettingEntries

This commit is contained in:
Karl Erik Õunapuu 2020-08-11 12:09:01 +03:00
parent a0c21d005e
commit 4f59900367

View file

@ -2,6 +2,7 @@ class SettingEntry < ApplicationRecord
validates :code, presence: true, uniqueness: true validates :code, presence: true, uniqueness: true
validates :value, presence: true validates :value, presence: true
validates :format, presence: true validates :format, presence: true
validates :group, presence: true
validate :valid_value_format validate :valid_value_format
VALUE_FORMATS = { VALUE_FORMATS = {
@ -12,6 +13,24 @@ class SettingEntry < ApplicationRecord
array: :array_format, array: :array_format,
}.with_indifferent_access.freeze }.with_indifferent_access.freeze
def retrieve
method = VALUE_FORMATS[format]
send(method)
end
def self.groups
SettingEntry.all.pluck(:group).uniq
end
def self.method_missing(method, *args)
super(method, *args)
rescue NoMethodError
raise NoMethodError if method.to_s.include? '='
SettingEntry.find_by!(code: method.to_s).retrieve
end
# Validators
def valid_value_format def valid_value_format
formats = VALUE_FORMATS.with_indifferent_access formats = VALUE_FORMATS.with_indifferent_access
errors.add(:format, :invalid) unless formats.keys.any? format errors.add(:format, :invalid) unless formats.keys.any? format
@ -36,17 +55,4 @@ class SettingEntry < ApplicationRecord
def array_format def array_format
JSON.parse(value).to_a JSON.parse(value).to_a
end end
def retrieve
method = VALUE_FORMATS[format]
send(method)
end
def self.method_missing(method, *args)
super(method, *args)
rescue NoMethodError
raise NoMethodError if method.to_s.include? '='
SettingEntry.find_by!(code: method.to_s).retrieve
end
end end