Permalink
Browse files

Merge pull request #379 from bellthoven/record_toggle_field

Added the ability to toggle bolean fields in Records
  • Loading branch information...
2 parents 7e068ac + 7250be7 commit 8e20f6b7014423ceca6aae90a347c14d9c2a0a7d @josevalim josevalim committed Jul 8, 2012
Showing with 22 additions and 2 deletions.
  1. +13 −1 lib/elixir/lib/record.ex
  2. +9 −1 lib/elixir/test/erlang/record_test.erl
View
@@ -318,5 +318,17 @@ defmodule Record.Definition do
end
end
+ def extension_for(key, default, i) when is_boolean(default) do
+ bin_key = atom_to_binary(key)
+ toggle = :"toggle_#{bin_key}"
+
+ quote do
+ def unquote(toggle).(value // false, record) do
+ current = :erlang.element(unquote(i), record)
+ :erlang.setelement(unquote(i), record, not current)
+ end
+ end
+ end
+
def extension_for(_, _, _), do: nil
-end
+end
@@ -58,4 +58,12 @@ record_increment_test() ->
{ { '__MAIN__-Foo', 10 }, _ } = eval("Foo.new.increment_a 10"),
{ { '__MAIN__-Foo', -2 }, _ } = eval("Foo.new.increment_a -2")
end,
- test_helper:run_and_remove(F, ['__MAIN__-Foo']).
+ test_helper:run_and_remove(F, ['__MAIN__-Foo']).
+
+record_toggle_test() ->
+ F = fun() ->
+ eval("defrecord Foo, a: false, b: true"),
+ { { '__MAIN__-Foo', true, true }, _ } = eval("Foo.new.toggle_a"),
+ { { '__MAIN__-Foo', false, false }, _ } = eval("Foo.new.toggle_b")
+ end,
+ test_helper:run_and_remove(F, ['__MAIN__-Foo']).

0 comments on commit 8e20f6b

Please sign in to comment.