Просмотр исходного кода

Support for empty values in yesno filter

The previous implementation was over specified and didn't support empty
strings as yesno options.

This implementation uses binary:split/3, which is as efficient as
string:tokens/2 but returns empty tokens.

See https://github.com/gar1t/erlang-bench/blob/master/comma-parse.escript for
details on parsing implementations.

This commit removes the odd conversion of Bool to a list, which was never
used in yesno_io.

This change returns a *binary* value, which may be contrary to the spirit
of the template implementation. If this is the case, the the result can be
easily converted to a list (a seeming waste of cycles, but perhaps there's
a good reason for it).
Garrett Smith 12 лет назад
Родитель
Сommit
3ebe859180
1 измененных файлов с 8 добавлено и 17 удалено
  1. 8 17
      src/erlydtl_filters.erl

+ 8 - 17
src/erlydtl_filters.erl

@@ -867,12 +867,10 @@ wordwrap(Input, Number) when is_list(Input) ->
     wordwrap(Input, [], [], 0, Number).
 
 %% @doc Given a string mapping values for true, false and (optionally) undefined, returns one of those strings according to the value.
-yesno(Bool, Choices) when is_binary(Bool) ->
-    yesno_io(binary_to_list(Bool), Choices);
 yesno(Bool, Choices) when is_binary(Choices) ->
-    yesno_io(Bool, binary_to_list(Choices));
+    yesno_io(Bool, Choices);
 yesno(Bool, Choices) when is_list(Choices) ->
-    yesno_io(Bool, Choices).
+    yesno_io(Bool, list_to_binary(Choices)).
 
 % internal
 
@@ -1206,19 +1204,12 @@ process_binary_match(Pre, Insertion, SizePost, Post) ->
     end.
 
 yesno_io(Bool, Choices) ->
-    %%       io:format("Bool, Choices: ~p, ~p ~n",[Bool, Choices]),
-    Terms = string:tokens(Choices, ","),
-    case Bool of
-        true ->
-            lists:nth(1, Terms);
-        false ->
-            lists:nth(2, Terms);
-        undefined when erlang:length(Terms) == 2 -> % (converts undefined to false if no mapping for undefined is given)
-            lists:nth(2, Terms);
-        undefined when erlang:length(Terms) == 3 ->
-            lists:nth(3, Terms);
-        _ ->
-            error
+    case {Bool, binary:split(Choices, <<",">>, [global])} of
+        {true, [T|_]} -> T;
+        {false, [_,F|_]} -> F;
+        {undefined, [_,_,U|_]} -> U;
+        {undefined, [_,F|_]} -> F;
+        _ -> error
     end.
 
 %% unjoin == split in other languages; inverse of join