Skip to content

Instantly share code, notes, and snippets.

@s-shin
Last active February 10, 2016 10:20
Show Gist options
  • Save s-shin/cf4004f12e0228a483d6 to your computer and use it in GitHub Desktop.
Save s-shin/cf4004f12e0228a483d6 to your computer and use it in GitHub Desktop.
Very simple validator.
require 'active_support'
require 'active_support/core_ext'
module Tenuki
class Validator
def initialize(field, value)
@field = field
@value = value
end
def required
tmpl('is required') if @value.nil?
end
def string
tmpl('should be a string') unless @value.is_a? String
end
def integer
tmpl('should be an integer') unless @value.is_a? Integer
end
def array(empty_ok: false, type: nil)
return tmpl('should be an array') unless @value.is_a? Array
unless empty_ok
return tmpl('should not be empty') if @value.empty?
end
unless type
ok = @value.index {|x| !x.is_a?(type)}.nil?
return tmpl("should contain only #{type} values") unless ok
end
end
def implemented(path_fmt)
path = path_fmt % @value
begin
require path
path.camelize.constantize
return nil
rescue LoadError => e
rescue => e
end
return tmpl("(#{path}) is not implemented: #{e.to_s}")
end
def custom(&block)
instance_eval { block.call }
end
def tmpl(str)
"'#{@field}: #{@value}' #{str}"
end
private :tmpl
class SingleErrorChain
attr_reader :error
def initialize(field, value)
@v = Validator.new(field, value)
@error = nil
end
def method_missing(name, *args, &block)
@error ||= @v.send(name, *args) { block.call }
return self
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment