Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions lib/phoenix/controller.ex
Original file line number Diff line number Diff line change
Expand Up @@ -1891,16 +1891,27 @@ defmodule Phoenix.Controller do

@doc """
Assigns multiple key-value pairs to the connection.
Accepts a keyword list, a map, or a single-argument function.

This function accepts a map or keyword list of assigns and merges them into
the connection's assigns. It is equivalent to calling `Plug.Conn.assign/3`
multiple times.

If a function is given, it takes the current assigns as an argument and its return
value will be merged into the current assigns.

## Examples

assign(conn, name: "Alice", role: :admin)
assign(conn, %{name: "Alice", role: :admin})
assign(conn, fn %{name: name, logo: logo} -> %{title: Enum.join([name, logo], " | ")} end)
"""
def assign(conn, keyword_or_map_or_fun)

def assign(conn, fun) when is_function(fun, 1) do
assign(conn, fun.(conn.assigns))
end

defdelegate assign(conn, assigns), to: Plug.Conn, as: :merge_assigns

@doc false
Expand Down
20 changes: 20 additions & 0 deletions test/phoenix/controller/controller_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -994,4 +994,24 @@ defmodule Phoenix.Controller.ControllerTest do
assert current_url(conn, %{three: 3}) == "https://www.example.com/foo?three=3"
end
end

describe "assign/2" do
test "merges assigns" do
conn = conn(:get, "/")

refute conn.assigns[:foo]

conn = assign(conn, %{foo: :bar})
assert conn.assigns.foo == :bar

conn = assign(conn, bar: :baz)
assert conn.assigns.foo == :bar
assert conn.assigns.bar == :baz

conn = assign(conn, fn %{foo: :bar} -> [baz: :quux] end)
assert conn.assigns.foo == :bar
assert conn.assigns.bar == :baz
assert conn.assigns.baz == :quux
end
end
end
Loading