-
Notifications
You must be signed in to change notification settings - Fork 3k
Accept function in Phoenix.Socket.assign/2
#6530
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Phoenix.Socket.assign_lazy/3
|
Thanks for the PR! I am not sure if I feel this is one of the cases where it is probably better to break the pipeline apart (or, as you said, use custom functions). |
|
Thanks for the feedback, @josevalim. def assign(%Socket{} = socket, fun) when is_function(fun, 1) do
Map.update!(socket, :assigns, &Map.merge(&1, Map.new(fun.(&1))))
endThis way, the example from the description will look like socket
|> assign_strcut1()
|> assign_struct2()
|> assign(%{struct1: struct1, struct2: struct2} -> [title: "#{strcut1.name} #{strcut2.name}")] end) |
|
That would work, yes! |
|
@josevalim Done ✅ I've slightly adjusted the implementation, but it has a potential issue. But it looks shorter and cleaner. |
Phoenix.Socket.assign_lazy/3Phoenix.Socket.assign/2
|
🙌🏻 |
* Add Phoenix.Socket.assign_lazy/3 * Refactoring
This PR adds
assign_lazy/3toPhoenix.Socket(if you like the idea, I will add a similar change to thePhoenix.Componentmodule in thephoenix_live_view).It is quite often that you need to update the socket based on the value that it is already in
assigns.For more complicated things, this could be handled with private functions, but this
assign_lazy/3is useful when you need something very simple.It is similar to the
assign_new/3, but it assigns the value even if the givenkeyexists.