augnustin

augnustin

Unquote with parameter in block

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

Marked As Solved

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.

Also Liked

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:

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.

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

Where Next?

Popular in Questions Top

lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
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
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
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
William
I would like to know that is there any online source for learning Phoenix Framework for building E-Commerce Store? Any advantage on build...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
AstonJ
You’re a programmer, so you don’t need spoon feeding with the conventional drivel about “this is an integer.” No. You need to know what’s...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

We're in Beta

About us Mission Statement