Permalink
Browse files

Return nil in decode_query (according to its docs) and allow dict to …

…be passed as argument
  • Loading branch information...
1 parent 463c588 commit 72b0e5fc144404d6b090ec641061fdb411361642 @josevalim josevalim committed May 6, 2012
Showing with 18 additions and 18 deletions.
  1. +11 −12 lib/uri.ex
  2. +7 −6 test/elixir/uri_test.exs
View
23 lib/uri.ex
@@ -28,26 +28,25 @@ defmodule URI do
Returns nil if the query string is malformed.
"""
- def decode_query(q) do
- # If the string is blank, return an empty dict
- empty_dict = Orddict.new
- if Regex.match?(%r"^\s*$", q) do
- empty_dict
+ def decode_query(q, dict // Orddict.new) do
+ if Regex.match?(%r/^\s*$/, q) do
+ dict
else:
parts = Regex.split %r/&/, to_binary(q)
- # Set up a try block to return quickly from List.foldl in case of an error
+ impl = Dict.__impl_for__!(dict)
+
try do
- List.foldl parts, empty_dict, fn(kvstr, dict) ->
+ List.foldl parts, dict, fn(kvstr, acc) ->
pair = case Regex.split(%r/=/, kvstr) do
- match: [ key, value ] when size(key) > 0
+ match: [ key, value ] when key != ""
{ decode(key), decode(value) }
else:
- throw { :error, "Malformed query string" }
+ throw :malformed_query_string
end
- Dict.Orddict.Record.put dict, pair
+ impl.put acc, pair
end
- catch: x
- x
+ catch: :malformed_query_string
+ nil
end
end
end
View
13 test/elixir/uri_test.exs
@@ -29,18 +29,19 @@ defmodule URITest do
end
test :decode_query do
- error = { :error, "Malformed query string" }
-
assert URI.decode_query("q=search%20query&cookie=ab%26cd&block%20buster=") ==
Orddict.new [{"block buster", ""}, {"cookie", "ab&cd"}, {"q", "search query"}]
assert URI.decode_query("") == Orddict.new
assert URI.decode_query('list=works') == Orddict.new [{"list", "works"}]
- assert URI.decode_query("garbage") == error
- assert URI.decode_query("=value") == error
- assert URI.decode_query("something=weird=happening") == error
- assert URI.decode_query("something=weird%3Dhappening") == Orddict.new [{"something", "weird=happening"}]
+ assert URI.decode_query("", HashDict.new) == HashDict.new
+ assert URI.decode_query('list=works', HashDict.new) == HashDict.new [{"list", "works"}]
+ assert URI.decode_query("garbage") == nil
+ assert URI.decode_query("=value") == nil
+ assert URI.decode_query("something=weird=happening") == nil
+
+ assert URI.decode_query("something=weird%3Dhappening") == Orddict.new [{"something", "weird=happening"}]
end
test :decode do

0 comments on commit 72b0e5f

Please sign in to comment.