Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Refactor type validators to be dynamically created

  • Loading branch information...
commit 42faea44de77d3b47f8532e33d4e51b9ba2ba2b5 1 parent d0f615b
@christoffer authored
Showing with 27 additions and 41 deletions.
  1. +27 −41 lib/params_validator/validator/type.rb
View
68 lib/params_validator/validator/type.rb
@@ -1,63 +1,49 @@
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
+ 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
Please sign in to comment.
Something went wrong with that request. Please try again.