1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Make assert_valid_keys slightly faster.

This commit is contained in:
thedarkone 2010-09-24 23:21:59 +02:00
parent 4c360c15e5
commit 77efc20a54
2 changed files with 7 additions and 5 deletions

View file

@ -35,11 +35,13 @@ class Hash
# as keys, this will fail. # as keys, this will fail.
# #
# ==== Examples # ==== Examples
# { :name => "Rob", :years => "28" }.assert_valid_keys(:name, :age) # => raises "ArgumentError: Unknown key(s): years" # { :name => "Rob", :years => "28" }.assert_valid_keys(:name, :age) # => raises "ArgumentError: Unknown key: years"
# { :name => "Rob", :age => "28" }.assert_valid_keys("name", "age") # => raises "ArgumentError: Unknown key(s): name, age" # { :name => "Rob", :age => "28" }.assert_valid_keys("name", "age") # => raises "ArgumentError: Unknown key: name"
# { :name => "Rob", :age => "28" }.assert_valid_keys(:name, :age) # => passes, raises nothing # { :name => "Rob", :age => "28" }.assert_valid_keys(:name, :age) # => passes, raises nothing
def assert_valid_keys(*valid_keys) def assert_valid_keys(*valid_keys)
unknown_keys = keys - valid_keys.flatten valid_keys.flatten!
raise(ArgumentError, "Unknown key(s): #{unknown_keys.join(", ")}") unless unknown_keys.empty? each_key do |k|
raise(ArgumentError, "Unknown key: #{k}") unless valid_keys.include?(k)
end
end end
end end

View file

@ -282,7 +282,7 @@ class HashExtTest < Test::Unit::TestCase
{ :failure => "stuff", :funny => "business" }.assert_valid_keys(:failure, :funny) { :failure => "stuff", :funny => "business" }.assert_valid_keys(:failure, :funny)
end end
assert_raise(ArgumentError, "Unknown key(s): failore") do assert_raise(ArgumentError, "Unknown key: failore") do
{ :failore => "stuff", :funny => "business" }.assert_valid_keys([ :failure, :funny ]) { :failore => "stuff", :funny => "business" }.assert_valid_keys([ :failure, :funny ])
{ :failore => "stuff", :funny => "business" }.assert_valid_keys(:failure, :funny) { :failore => "stuff", :funny => "business" }.assert_valid_keys(:failure, :funny)
end end