Skip to content

Commit 35cc80b

Browse files
committed
followup for #6530
1 parent dca7563 commit 35cc80b

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

lib/phoenix/controller.ex

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1891,16 +1891,27 @@ defmodule Phoenix.Controller do
18911891

18921892
@doc """
18931893
Assigns multiple key-value pairs to the connection.
1894+
Accepts a keyword list, a map, or a single-argument function.
18941895
18951896
This function accepts a map or keyword list of assigns and merges them into
18961897
the connection's assigns. It is equivalent to calling `Plug.Conn.assign/3`
18971898
multiple times.
18981899
1900+
If a function is given, it takes the current assigns as an argument and its return
1901+
value will be merged into the current assigns.
1902+
18991903
## Examples
19001904
19011905
assign(conn, name: "Alice", role: :admin)
19021906
assign(conn, %{name: "Alice", role: :admin})
1907+
assign(conn, fn %{name: name, logo: logo} -> %{title: Enum.join([name, logo], " | ")} end)
19031908
"""
1909+
def assign(conn, keyword_or_map_or_fun)
1910+
1911+
def assign(conn, fun) when is_function(fun, 1) do
1912+
assign(conn, fun.(conn.assigns))
1913+
end
1914+
19041915
defdelegate assign(conn, assigns), to: Plug.Conn, as: :merge_assigns
19051916

19061917
@doc false

test/phoenix/controller/controller_test.exs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -994,4 +994,24 @@ defmodule Phoenix.Controller.ControllerTest do
994994
assert current_url(conn, %{three: 3}) == "https://www.example.com/foo?three=3"
995995
end
996996
end
997+
998+
describe "assign/2" do
999+
test "merges assigns" do
1000+
conn = conn(:get, "/")
1001+
1002+
refute conn.assigns[:foo]
1003+
1004+
conn = assign(conn, %{foo: :bar})
1005+
assert conn.assigns.foo == :bar
1006+
1007+
conn = assign(conn, bar: :baz)
1008+
assert conn.assigns.foo == :bar
1009+
assert conn.assigns.bar == :baz
1010+
1011+
conn = assign(conn, fn %{foo: :bar} -> [baz: :quux] end)
1012+
assert conn.assigns.foo == :bar
1013+
assert conn.assigns.bar == :baz
1014+
assert conn.assigns.baz == :quux
1015+
end
1016+
end
9971017
end

0 commit comments

Comments
 (0)