Browse Source

Support iterating over Ecto has_many associations

Evan Miller 11 years ago
parent
commit
7148ba1614
2 changed files with 14 additions and 6 deletions
  1. 1 4
      src/erlydtl_compiler.erl
  2. 13 2
      src/erlydtl_runtime.erl

+ 1 - 4
src/erlydtl_compiler.erl

@@ -1300,10 +1300,7 @@ for_loop_ast(IteratorList, LoopValue, IsReversed, Contents, {EmptyContentsAst, E
 
 
     {{LoopValueAst, LoopValueInfo}, TreeWalker2} = value_ast(LoopValue, false, true, Context, TreeWalker1),
     {{LoopValueAst, LoopValueInfo}, TreeWalker2} = value_ast(LoopValue, false, true, Context, TreeWalker1),
 
 
-    LoopValueAst0 = case IsReversed of
-			true -> erl_syntax:application(erl_syntax:atom(lists), erl_syntax:atom(reverse), [LoopValueAst]);
-			false -> LoopValueAst
-		    end,
+    LoopValueAst0 = erl_syntax:application(erl_syntax:atom(erlydtl_runtime), erl_syntax:atom(to_list), [LoopValueAst, erl_syntax:atom(IsReversed)]),
 
 
     CounterVars0 = case resolve_scoped_variable_ast('forloop', Context) of
     CounterVars0 = case resolve_scoped_variable_ast('forloop', Context) of
 		       undefined ->
 		       undefined ->

+ 13 - 2
src/erlydtl_runtime.erl

@@ -34,8 +34,7 @@ find_value(Key, {GBSize, GBData}) when is_integer(GBSize) ->
             undefined
             undefined
     end;
     end;
 find_value(Key, Tuple) when is_tuple(Tuple) ->
 find_value(Key, Tuple) when is_tuple(Tuple) ->
-    Module = element(1, Tuple),
-    case Module of
+    case element(1, Tuple) of
         dict -> 
         dict -> 
             case dict:find(Key, Tuple) of
             case dict:find(Key, Tuple) of
                 {ok, Val} ->
                 {ok, Val} ->
@@ -203,6 +202,18 @@ stringify_final([El | Rest], Out, true = BinaryStrings) when is_tuple(El) ->
 stringify_final([El | Rest], Out, BinaryStrings) ->
 stringify_final([El | Rest], Out, BinaryStrings) ->
     stringify_final(Rest, [El | Out], BinaryStrings).
     stringify_final(Rest, [El | Out], BinaryStrings).
 
 
+to_list(Value, true) ->
+    lists:reverse(to_list(Value, false));
+to_list(Value, false) when is_list(Value) ->
+    Value;
+to_list(Value, false) when is_tuple(Value) ->
+    case element(1, Value) of
+        'Elixir.Ecto.Associations.HasMany' ->
+            Value:to_list();
+        _ ->
+            tuple_to_list(Value)
+    end.
+
 init_counter_stats(List) ->
 init_counter_stats(List) ->
     init_counter_stats(List, undefined).
     init_counter_stats(List, undefined).