augnustin

augnustin

So I have this macro:

  defmacro content(_opts \\ [], do: block) do
    quote location: :keep do
      def page_view(var!(conn)) do
        import Kernel, except: [div: 2, to_string: 1]
        import ExAdmin.ViewHelpers
        use Xain
        _ = var!(conn)

        markup safe: true do
          unquote(block)
        end
      end
    end
  end

Which is used like that:

    content do
       # Whatever code
    end

How can I pass the conn variable to the content block?

    content do
      IO.inspect(conn)
    end

Can’t make it work. :frowning:

Thanks

Showing Posts 1 to 10

LostKobrakai

LostKobrakai

defmodule TestXain do
  defmacro content(do: block) do
    block =
      quote do
        _ = var!(conn)
        import Kernel, except: [div: 2, to_string: 1]
        use Xain

        markup safe: true do
          unquote(block)
        end
      end

    quote location: :keep do
      def page_view(var!(conn)), do: unquote(block)
    end
  end
end


defmodule TestXain.View do
  import TestXain

  content do
    IO.inspect(conn)
  end
end

iex(1)> TestXain.View.page_view(1)
1
{:safe, "1"}

This seems to work fine for me and circumvents the whole problem of unquote fragments.

augnustin

augnustin OP

Thanks a lot for your answers.

This works like a charm. It even works with the original version, which I did not think of testing since I could not imagine it would.

How does the block knows about conn? For a almost functional language that is elixir, this is amazing to see a named variable coming in like this!

But it does solve my issue, which is great! :sunglasses:

LostKobrakai

LostKobrakai

Using var! makes the variable unhygienic, so it bleeds into the inner blocks scope. If you consider the resulting AST you’ll notice, that the inner block just refers to a variable like this {:conn, [], Some.Module}, where the last part is the context of the variable. var! makes it so that the contexts match, while without that they won’t.

The resulting AST doesn’t really care if it came out of a macro or not. With it it looks like you wrote:

      def page_view(conn) do
        import Kernel, except: [div: 2, to_string: 1]
        import ExAdmin.ViewHelpers
        use Xain
        _ = conn

        markup safe: true do
          IO.inspect(conn)
        end
      end

Which is obviously fine code.

augnustin

augnustin OP

Yes, I imagined this was equivalent to:

        markup safe: true do
          IO.inspect(conn)
        end

The only thing that makes me slightly uncomfortable is that the variable is named so one needs to read the calling code (or the doc) to know what variables are available but I guess that’s how things go!

Thanks for your support :smile:

LostKobrakai

LostKobrakai

You could build the macro to be called like that:

content(conn) do
  IO.inspect(conn)
end

or

content conn do
 IO.inspect(conn)
end

I’d not jump to unhygienic variables without a good reason.

OvermindDL1

OvermindDL1

I personally prefer something like:

content do
  conn -> IO.inspect(conn)
end

You can either decompose it to grab the head as the var, or just use it as a case context with full matching and all, which is also so easy to do in quotes. :slight_smile:

augnustin

augnustin OP

Those two solutions seem much cleaner in terms of readability.

That said, I’m going for the undeclared version since it is the original from a lib (ex_admin) and I don’t need to change it here.

silviurosu

silviurosu

I like very much your idea. Can you give an example how can I write a macro like this?
I would like to be able to call it like this:

wrap_with_connection do
   channel -> publish_on_existing_channel(channel, @exchange, @outcome_routing_key, outcome_payload)
end

I can not figure out how to write the macro. What I have by now is:

defmodule Example do
  def init_rabbitmq_channel do
    ...
  end

  def close_rabbitmq_channel(channel) do
    ....
  end

  def publish_on_existing_channel(channel, exchange, routing_key, payload) do
    .....
  end

  defmacro wrap_with_connection(do: block) do
    quote do
      var!(channel) = init_rabbitmq_channel()
      unquote(block)
      close_rabbitmq_channel(channel)
    end
  end
end
OvermindDL1

OvermindDL1

You’d want to instead do this function as something like this instead:

  defmacro wrap_with_connection(do: block) do
    quote do
      channel = init_rabbitmq_channel() # This is a different channel than what the user will match on
      case channel do
        unquote(block) # This might need to be `unquote_splice`, I forget, I usually use ast tuples...
      end
      close_rabbitmq_channel(channel)
    end
  end

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
ChrisAmelia
I’ve got trouble wrapping my head around the order in which functions are called in this snippet (from Phoenix’s authentication): toke...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews