Browse Source

Merge pull request #52 from essen/intcomma

Add a contrib_humanize module for the intcomma filter
Evan Miller 12 years ago
parent
commit
6d1fcaf7ed
2 changed files with 25 additions and 1 deletions
  1. 18 0
      src/erlydtl_contrib_humanize.erl
  2. 7 1
      tests/src/erlydtl_unittests.erl

+ 18 - 0
src/erlydtl_contrib_humanize.erl

@@ -0,0 +1,18 @@
+-module(erlydtl_contrib_humanize).
+
+-export([intcomma/1]).
+
+intcomma(Value) when is_integer(Value) ->
+	intcomma(integer_to_list(Value));
+intcomma(Value) ->
+	ValueBin = iolist_to_binary(Value),
+	intcomma(ValueBin, size(ValueBin) rem 3, <<>>).
+
+intcomma(<<>>, _, Acc) ->
+	Acc;
+intcomma(<< C, Rest/bits >>, 0, <<>>) ->
+	intcomma(Rest, 2, << C >>);
+intcomma(<< C, Rest/bits >>, 0, Acc) ->
+	intcomma(Rest, 2, << Acc/binary, $,, C >>);
+intcomma(<< C, Rest/bits >>, N, Acc) ->
+	intcomma(Rest, N - 1, << Acc/binary, C >>).

+ 7 - 1
tests/src/erlydtl_unittests.erl

@@ -1059,12 +1059,18 @@ tests() ->
      {"unicode", [
      {"unicode", [
              {"(tm) somewhere",
              {"(tm) somewhere",
                  <<"™">>, [], <<"™">>}
                  <<"™">>, [], <<"™">>}
+        ]},
+     {"contrib_humanize", [
+             {"intcomma",
+                 <<"{{ a|intcomma }} {{ b|intcomma }} {{ c|intcomma }} {{ d|intcomma }}">>,
+                     [{a, 999}, {b, 123456789}, {c, 12345}, {d, 1234567890}],
+                     <<"999 123,456,789 12,345 1,234,567,890">>}
         ]}
         ]}
     ].
     ].
  
  
 run_tests() ->
 run_tests() ->
     io:format("Running unit tests...~n"),
     io:format("Running unit tests...~n"),
-    DefaultOptions = [],
+    DefaultOptions = [{custom_filters_modules, [erlydtl_contrib_humanize]}],
     Failures = lists:foldl(
     Failures = lists:foldl(
         fun({Group, Assertions}, GroupAcc) ->
         fun({Group, Assertions}, GroupAcc) ->
                 io:format(" Test group ~p...~n", [Group]),
                 io:format(" Test group ~p...~n", [Group]),