Disallow instance method names as Setting code

This commit is contained in:
Karl Erik Õunapuu 2020-08-12 17:35:49 +03:00
parent abea8abe84
commit 8683964d22
2 changed files with 19 additions and 4 deletions

View file

@ -1,10 +1,10 @@
class SettingEntry < ApplicationRecord class SettingEntry < ApplicationRecord
include Versions include Versions
validates :code, presence: true, uniqueness: true validates :code, presence: true, uniqueness: true, format: { with: /\A([a-z])[a-z|_]+[a-z]\z/ }
validates :format, presence: true validates :format, presence: true
validates :group, presence: true validates :group, presence: true
validate :valid_value_format validate :validate_value_format
validates_format_of :code, with: /([a-z])[a-z|_]+[a-z]/ validate :validate_code_is_not_using_reserved_name
VALUE_FORMATS = { VALUE_FORMATS = {
string: :string_format, string: :string_format,
@ -44,7 +44,13 @@ class SettingEntry < ApplicationRecord
end end
# Validators # Validators
def valid_value_format def validate_code_is_not_using_reserved_name
disallowed = []
ActiveRecord::Base.instance_methods.sort.each { |m| disallowed << m.to_s }
errors.add(:code, :invalid) if disallowed.include? code
end
def validate_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
end end

View file

@ -35,6 +35,15 @@ class SettingEntryTest < ActiveSupport::TestCase
@new_setting.code = 'a b' @new_setting.code = 'a b'
assert_not @new_setting.valid? assert_not @new_setting.valid?
@new_setting.code = 'ab_'
assert_not @new_setting.valid?
@new_setting.code = '_ab'
assert_not @new_setting.valid?
@new_setting.code = '1_2'
assert_not @new_setting.valid?
@new_setting.code = 'a_b' @new_setting.code = 'a_b'
assert @new_setting.valid? assert @new_setting.valid?
end end