fceruti

fceruti

Small useful macro |> case_continue

I just wanted to share with you a small macro that has cleaned up many many lines of code for me.

Basically in my contexts I had this kind of code everywhere

      |> Repo.transaction()
      |> case do
        {:ok, %{goal: goal}} = result ->
          PubSub.broadcast_goal_created(user, goal)
          result

        error ->
          error
      end

A possible solution would be to add maybe functions

      |> Repo.transaction()
      |> maybe_broadcast_goal_created(user)

..

def maybe_broadcast_goal_created({:ok, %{goal: goal}} = result, user) do
  PubSub.broadcast_goal_created(user, goal)
  result
end

def maybe_broadcast_goal_created(result, user), do: result

Which is not ideal since I’d have to create one pair for each function in context.

Macros to the rescue!

Inspired by how IO.inspect prints and keeps moving, I created case_continue, which runs case, ignores it’s result and continues the pipe as if it was never there.

defmodule Timetask.Helpers.Macros do
  defmacro case_continue(prev, do: block) do
    quote do
      case unquote(prev) do
        unquote(block ++ [{:->, [], [[{:_, [], nil}], nil]}])
      end

      unquote(prev)
    end
  end
end

Now I can write it like this.

      |> Repo.transaction()
      |> case_continue do
        {:ok, %{goal: goal}} -> PubSub.broadcast_goal_created(user, goal)
      end

Much nicer huh? What do you think? Do you like the name? I also had in mind case_bridge or case_skip.

Most Liked

RudManusachi

RudManusachi

  1. Piping into case lately became a subject for debates :smiling_imp: (see don’t pipe into case statements)

  2. Macros are awesome! ..mostly for stuff I do on my own :neutral_face:
    Especially adding up to the language syntax meant to be commonly used across the project might not be obvious to the team who work with the code.

    Macros should only be used as a last resort. Remember that explicit is better than implicit . Clear code is better than concise code.

    _https://elixir-lang.org/getting-started/meta/macros.html#foreword_


Whenever I notice case of just two branches one of which just returns the input - I think of with

    result =
      ...
      |> Repo.transaction()

    with {:ok, %{goal: goal}} <- result do
      PubSub.broadcast_goal_created(user, goal)
      result
    end

With your macro we can handle more than just one happy path, though.

al2o3cr

al2o3cr

I don’t find the error -> boilerplate that annoying, personally. I always prefer to unpack results (both successand error) from passing Ecto.Multi to Repo.transaction as close to the transaction as possible, because otherwise operation names become an accidental part of the function’s interface.

I’m also not sure how the above macro accomplishes the task - it seems like a result other than {:ok, %{goal: _}} will fail to match in the generated case statement.

Sebb

Sebb

Where is the debate? This just says: dont do it!

Last Post!

ityonemo

ityonemo

unfortunately, using bind_quoted disables the use of unquotes. So you might have to do this:

  defmacro maybe_case(prev, do: block) do
    quote do
      prev = unquote(prev)
      case prev do
        unquote(block ++ [{:->, [], [[{:_, [], nil}], nil]}])
      end
    end
  end

Where Next?

Popular in Discussions Top

New
scouten
I’m looking for a host for the server part of a small (personal) side project that I’m working on. It’s currently written in Node.js and ...
New
AstonJ
Are there any Elixir or Erlang libraries that help with this? I’ve been thinking how streaming services like twitch have exploded recentl...
New
AstonJ
If a newbie asked you about Phoenix Contexts, how would you explain the basics to them? Feel free to be as concise or in-depth as you li...
New
AstonJ
I’ve just started the Phoenix part of the utterly brilliant online course by @pragdave. On generating the Phoenix app he uses the --no-ec...
New
rower687
Hi all, I’ve been reading a lot about the “let it crash” term and how supervising processes and the whole messaging passing make an elixi...
New
chuck
Let me start by stating an assumption: Phoenix is a great approach to building REST APIs. There are many reasons for this, but I will ass...
New

Other popular topics Top

Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 40165 209
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 44265 214
New

We're in Beta

About us Mission Statement