163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
|
# File 'lib/focuslight/validator.rb', line 163
def self.rule(type, *args)
args.flatten!
case type
when :not_blank
Rule.new(->(v){not v.nil? and not v.strip.empty?}, "missing or blank", :strip)
when :choice
Rule.new(->(v){args.include?(v)}, "invalid value")
when :int
Rule.new(->(v){v =~ /^-?\d+$/}, "invalid integer", :to_i)
when :uint
Rule.new(->(v){v =~ /^\d+$/}, "invalid integer (>= 0)", :to_i)
when :natural
Rule.new(->(v){v =~ /^\d+$/ && v.to_i >= 1}, "invalid integer (>= 1)", :to_i)
when :float, :double, :real
Rule.new(->(v){v =~ /^\-?(\d+\.?\d*|\.\d+)(e[+-]\d+)?$/}, "invalid floating point num", :to_f)
when :int_range
Rule.new(->(v){args.first.include?(v.to_i)}, "invalid number in range #{args.first}", :to_i)
when :bool
Rule.new(->(v){v =~ /^(0|1|true|false)$/i}, "invalid bool value", ->(v){!!(v =~ /^(1|true)$/i)})
when :regexp
Rule.new(->(v){v =~ args.first}, "invalid input for pattern #{args.first.source}")
when :lambda
Rule.new(*args)
else
raise ArgumentError, "unknown validator rule: #{type}"
end
end
|