Improve validations

This commit is contained in:
Alex Kotov 2023-09-30 23:59:59 +04:00
parent 2c7228c0e0
commit b0c7de3aae
Signed by: kotovalexarian
GPG key ID: 553C0EBBEB5D5F08
4 changed files with 25 additions and 23 deletions

View file

@ -17,4 +17,24 @@ require_relative 'referator/script'
module Referator
NAME_RE = /\A\w+(_\w+)*\z/
SLUG_RE = /\A\w+(-\w+)*\z/
def self.validate_name!(name)
name.freeze
unless name.instance_of? Symbol
raise TypeError, "Expected #{Symbol}, got #{name.class}"
end
raise 'Invalid name' unless NAME_RE.match? name
name
end
def self.validate_slug!(slug)
slug.freeze
unless slug.instance_of? String
raise TypeError, "Expected #{String}, got #{slug.class}"
end
raise 'Invalid slug' unless SLUG_RE.match? slug
slug
end
end

View file

@ -16,8 +16,8 @@ module Referator
end
def register(name)
validate_name! name
raise 'Already exists' if names.index(name)
Referator.validate_name! name
raise 'Already exists' if names.index name
names << name
nil
@ -37,13 +37,6 @@ module Referator
@config = config
end
def validate_name!(name)
unless name.instance_of? Symbol
raise TypeError, "Expected #{Symbol}, got #{name.class}"
end
raise 'Invalid name' unless NAME_RE.match? name
end
end
end
end

View file

@ -18,7 +18,7 @@ module Referator
end
def register(name, **kwargs)
validate_name! name
Referator.validate_name! name
raise 'Already exists' if names.index(name) || scripts.key?(name)
script = Script.new(**kwargs.merge(workdir: config.workdir,
@ -55,13 +55,6 @@ module Referator
@config = config
end
def validate_name!(name)
unless name.instance_of? Symbol
raise TypeError, "Expected #{Symbol}, got #{name.class}"
end
raise 'Invalid name' unless NAME_RE.match? name
end
def script_vars(template: nil, format: nil, notes: nil)
{ template:, format:, notes: }.freeze
end

View file

@ -26,9 +26,7 @@ module Referator
private
def category=(category)
@category = String(category).to_sym.tap do |new_category|
raise 'Invalid category' unless NAME_RE.match? new_category
end
@category = Referator.validate_name! String(category).to_sym
end
def id=(id)
@ -36,9 +34,7 @@ module Referator
end
def slug=(slug)
@slug = String(slug).freeze.tap do |new_slug|
raise 'Invalid slug' unless SLUG_RE.match? new_slug
end
@slug = Referator.validate_slug! String slug
end
def data=(data)