Skip to content

Instantly share code, notes, and snippets.

@tatat
Created November 29, 2012 05:03
Show Gist options
  • Save tatat/4166911 to your computer and use it in GitHub Desktop.
Save tatat/4166911 to your computer and use it in GitHub Desktop.
こういうふうに文字列チェックしたい
module Nyan
class BaseValidator
def initialize(*values)
@values = values
@result = false
@or = false
@not = false
end
def and
@or = false
self
end
def or
@or = true
self
end
def not
@not = true
self
end
def to_b
!! @result
end
def method_missing(method, *args)
super unless /\?$/ =~ method.to_s
_method = method.to_s.sub(/\?$/, '').to_sym
if self.respond_to? _method
self.send(_method, *args).to_b
else
super
end
end
class << self
alias_method :is, :new
alias_method :does, :new
alias_method :are, :new
alias_method :do, :new
end
protected
def evaluate
return self if @or && @result || !@or && !@result
@result = @values.all? do |value|
(yield value) ^ @not
end
@or = false
@not = false
self
end
end
class StringValidator < BaseValidator
def initialize(*values)
super
@is_string = values.all? {|value| value.is_a? String}
@result = @is_string
end
def match(regexp)
evaluate {|value| (regexp =~ value) != nil}
end
def integer
match /^(?:-|\+)?[0-9]*$/
end
def float
match /^(?:-|\+)?[0-9]+\.[0-9]+$/
end
def yes
match /^(?:1|true|TRUE|True|T|t|yes|YES|Yes|Y|y)$/
end
protected
def evaluate
return self if !@is_string
super
end
end
module Validator
def is(*values)
values = values.length == 0 ? [self] : values
StringValidator.new(*values)
end
alias_method :does, :is
alias_method :are, :is
alias_method :do, :is
end
end
include Nyan::Validator
p is('nyan').not.yes? # => true
p is('y').not.yes? # => false
p is('999').integer? # => true
p does('nya', 'nyannya').match(/nyan/).and.match?(/nya$/) # => false
p does('nya', 'nyannya').match(/^nya/).and.match?(/nya$/) # => true
class String
include Nyan::Validator
end
p 'nyan'.is.yes? # => false
p 'y'.is.yes? # => true
p 'opopo'.is.not.integer? # => true
p '12345'.is.integer? # => true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment