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

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
restack_oslo
Hello, Please pardon me for any faux paux. I am 46 and this is my first time on a forum of any kind. I wanted to to get answers from tho...
New
pdgonzalez872
If this has been asked here before, please point me to where it was asked as I didn’t find it when I searched the forum. Maybe a mailing ...
New
Nvim
Anybody knows a comprehensive comparison of Django and Phoenix, thanks for the help. Where are they similar? Where do they differ the m...
New
Fl4m3Ph03n1x
Background A few days ago I was listening to The future of Elixir from Elixir Talks, with Dave Thomas (@pragdave ) and Brian Mitchell. I...
New
Rustixir
Hi everyone, im working on find best language/framework/system for high concurrency, high performance and stable performance after wor...
New
AstonJ
Can you believe the first professionally published Elixir book was published just 8 years ago? Since then I think we’ve seen more books f...
New

Other popular topics Top

nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 44778 311
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement