Skip to content

Commit

Permalink
Make nil as target be a noop
Browse files Browse the repository at this point in the history
  • Loading branch information
Serabe committed Mar 8, 2024
1 parent 82efca7 commit d63577f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
3 changes: 3 additions & 0 deletions lib/live_view_events/notify.ex
Original file line number Diff line number Diff line change
Expand Up @@ -149,11 +149,13 @@ defmodule LiveViewEvents.Notify do
@doc """
`notify_to/2` accepts a target and a message name. The target can be any of:
- `nil` would make it be a noop.
- `:self` to send to `self()`.
- A PID.
- A tuple of the form `{Module, "id"}` to send a message to a [`LiveView.Component`](`Phoenix.LiveView.Component`) in the same process.
- A tuple of the form `{pid, Module, "id"}` to send a message to a [`LiveView.Component`](`Phoenix.LiveView.Component`) in a different process.
"""
def notify_to(nil, _message), do: nil
def notify_to(:self, message), do: notify_to(self(), message)
def notify_to(pid, message) when is_pid(pid), do: send(pid, message)

Expand All @@ -167,6 +169,7 @@ defmodule LiveViewEvents.Notify do
In this case, the message sent would be a tuple with the `message` as first element and `params` as the
second one.
"""
def notify_to(nil, _message, _params), do: nil
def notify_to(:self, message, params), do: notify_to(self(), message, params)
def notify_to(pid, message, params) when is_pid(pid), do: send(pid, {message, params})

Expand Down
11 changes: 11 additions & 0 deletions test/live_view_events/notify_test.exs
Original file line number Diff line number Diff line change
@@ -1,2 +1,13 @@
defmodule LiveViewEvents.NotifyTest do
use ExUnit.Case

alias LiveViewEvents.Notify

test "notify_to/2 with `nil` target does not break" do
Notify.notify_to(nil, "event")
end

test "notify_to/3 with `nil` target does not break" do
Notify.notify_to(nil, "event", %{some: :params})
end
end

0 comments on commit d63577f

Please sign in to comment.