Navigation Menu

Skip to content

Commit

Permalink
Accept multiple expected types for parameter validation
Browse files Browse the repository at this point in the history
  • Loading branch information
piroor committed Feb 13, 2014
1 parent f1468e6 commit 1c2d5e7
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
18 changes: 12 additions & 6 deletions lib/droonga/catalog/base.rb
Expand Up @@ -178,13 +178,19 @@ def validate_required_parameter(value, name)
raise MissingRequiredParameter.new(name, @path) unless value
end

def validate_parameter_type(expected, value, name)
unless value.is_a?(expected)
raise MismatchedParameterType.new(name,
expected,
value.class,
@path)
def validate_parameter_type(expected_types, value, name)
expected_types = [expected_types] unless expected_types.is_a?(Array)

if expected_types.any? do |type|
value.is_a?(type)
end
return
end

raise MismatchedParameterType.new(name,
expected,
value.class,
@path)
end

def validate_valid_datetime(value, name)
Expand Down
13 changes: 11 additions & 2 deletions lib/droonga/catalog/errors.rb
Expand Up @@ -34,8 +34,17 @@ def initialize(name, path)
end

class MismatchedParameterType < ValidationError
def initialize(name, expected, actual, path)
super("\"#{name}\" must be a #{expected}, but a #{actual}.", path)
def initialize(name, expected_types, actual, path)
expected_types = [expected_types] unless expected_types.is_a?(Array)
message = nil
if expected_types.size == 1
message = "\"#{name}\" must be #{expected_types.first}, " +
"but #{actual}."
else
message = "\"#{name}\" must be #{expected_types.join(" or ")}, " +
"but #{actual}."
end
super(message, path)
end
end

Expand Down

0 comments on commit 1c2d5e7

Please sign in to comment.