fceruti

fceruti

Macro Monday - Share your macros!

Happy Macro Monday to everyone!

I was wonder what kinds of crafty macros you think are awesome and have come to rely upon.

I’ll go first:

Sigil m


  defmacro sigil_m({:<<>>, _line, [string]}, []) do
    spec =
      string
      |> String.split()
      |> Stream.map(&String.to_atom/1)
      |> Enum.map(&{&1, {&1, [], nil}})

    {:%{}, [], spec}
  end

This one I copy-pasted from the web (can’t remember the origin) and it’s truly a killer in readability and speed of development.

I use it in many places, but on tests & liveview really shines:

Tests

test "happy path", ~%{user: user, project: project, task_1: task_1, task_2: task_2} do
test "happy path", ~m{user project task_1 task_2} do

Liveview

%{current_user: current_user,  project: project} = socket.assigns
~m{current_user project} = socket.assigns

Maybe Case

This one is “my own creation” (quotes apply as I received tons of help).

Think tap/1 meets case.

  defmacro maybe_case(prev, do: block) do
    quote do
      prev = unquote(prev)

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

      prev
    end
  end

The use I have for this is the following. In my context layer I have all this functions such as schedule_task, unschedule_task etc, which in principle all look something like this:

Multi.new()
|> Multi.run(...)
|> Multi.run(...)
|> Multi.run(...)
|> Repo.transaction()
|> case do
   {:ok, %{action: ...}} -> {:ok, ...}
   {:ok, %{action_2: ...}} -> {:ok, ...}
   {:error, %{action: ...}} -> {:error, ...}
end

That’s great until you want to introduce side effects like logging and pubsubing. I could of course capture the result of the transaction, make conditional statements for publish & log and then shape the response.

results = Multi.new()
  |> Multi.run(...)
  |> Multi.run(...)
  |> Multi.run(...)
  |> Repo.transaction()

case results do
  {:ok, _, _} -> PubSub.publish_change()
  {:error, _, _} -> Logger.error()
end

case results do
   {:ok, %{action: ...}} -> {:ok, ...}
   {:ok, %{action_2: ...}} -> {:ok, ...}
   {:error, %{action: ...}} -> {:error, ...}
end

But being a pipe-man myself, I decided I needed my code to look like this:

Multi.new()
|> Multi.run(...)
|> Multi.run(...)
|> Multi.run(...)
|> Repo.transaction()
|> maybe_case do
  {:ok, _} -> PubSubs.publish_change(...)
  {:error, _} -> Logger.error(...)
end
|> case do
   {:ok, %{action: ...}} -> {:ok, ...}
   {:ok, %{action_2: ...}} -> {:ok, ...}
   {:error, %{action: ...}} -> {:error, ...}
end

Now it’s your turn!

Most Liked

Nicd

Nicd

I don’t like macros. They’re obscure and inscrutable and irritating, and they get everywhere.

That said, I have two macros that I use to add type information to my code, my typed struct and typed Ecto schema macros. The latter is ugly and incomplete, but the former I can link for you: lib/geo_therminator/typed_struct.ex · 8fa72cbfa5b0402c46c53e13e5e994bf5a390f89 · Mikko Ahlroth / GeoTherminator · GitLab

I use it like this then:

defmodule Register do
  deftypedstruct(%{
    register_name: String.t(),
    register_value: {integer(), 0},
    timestamp: DateTime.t()
  })
end

It defines the struct, a @type t, and @enforce_keys for me all in one go. I copy it to every new project I start.

Where Next?

Popular in Discussions Top

PragTob
Hello everyone, I know we had quite some threads (read through lots of them) about background job processing but it remains a hotly deba...
New
mikl
I wanted to capitalize a string, and tried using String.capitalize(). That generally works well, until you try to capitalize a word like...
New
thojanssens1
It would be nice to be able to define a redirect from one route to another from the router.ex file. E.g.: redirect "/", UserController, ...
New
arpan
Hello everyone :wave: Today I am very excited to announce a project that I have been working on for almost 3 months now. The project is...
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
lucaong
Hello Elixir and Nerves community, I have been working for a while on an open-source embedded key-value database for Elixir, that I call...
230 14027 124
New
AlexMcConnell
The reason that Rails is as popular as it is is because it’s very easy for relatively inexperienced developers to get a lot of work done....
588 19652 166
New
shishini
I think this twitter post and youtube video didn’t get as much attention as I hoped I am still new to Elixir, so can’t really judge ...
New
und0ck3d
Hello everyone! A few days ago I’ve created a topic here about how people were creating CMSs with Elixir and Phoenix. I’ve been studying...
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

Other popular topics Top

malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
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
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 127089 1222
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
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

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement