Just a little nicer (imho) definitions for type validators #1

Merged
merged 2 commits into from Apr 17, 2012
@@ -1,63 +1,50 @@
module ParamsValidator
module Validator
- module TypeInteger
- def self.error_message; "is not of type integer"; end
- def self.valid?(value)
- return true unless Presence.valid?(value)
+ private
+
+ module Base
+ private
+ def define_type_validator(type_name, &block)
+ @type_name = type_name
+ @block = block
- begin
- Integer(value)
- true
- rescue
- false
+ def self.error_message
+ "is not of type #{@type_name.to_s.downcase}"
+ end
+
+ def self.valid?(value)
+ return true unless Presence.valid?(value)
+ return !!@block.call(value) rescue false
end
end
end
- module TypeFloat
- def self.error_message; "is not of type float"; end
+ public
- def self.valid?(value)
- return true unless Presence.valid?(value)
+ module TypeInteger
+ extend Base
+ define_type_validator('integer') { |value| Integer(value) }
+ end
- begin
- Float(value)
- true
- rescue
- false
- end
- end
+ module TypeFloat
+ extend Base
+ define_type_validator('float') { |value| Float(value) }
end
module TypeString
- def self.error_message; "is not of type string"; end
-
- def self.valid?(value)
- return true unless Presence.valid?(value)
-
- value.kind_of? String
- end
+ extend Base
+ define_type_validator('string') { |value| value.kind_of? String }
end
module TypeArray
- def self.error_message; "is not of type array"; end
-
- def self.valid?(value)
- return true unless Presence.valid?(value)
-
- value.kind_of? Array
- end
+ extend Base
+ define_type_validator('array') { |value| value.kind_of? Array }
end
module TypeHash
- def self.error_message; "is not of type hash"; end
-
- def self.valid?(value)
- return true unless Presence.valid?(value)
-
- value.kind_of? Hash
- end
+ extend Base
+ define_type_validator('hash') { |value| value.kind_of? Hash }
end
end
end