coen.bakker

coen.bakker

I was writing a macro for injecting internationalised routes into MyAppWeb.Router.

When using the Gettext macros, in contrast to the Gettext functions, the msgid argument must be a string at compile-time (see docs).

I am confused about why that’s not the case here:

defmodule MyAppWeb.LocaleRoutes do
  require MyAppWeb.Gettext
  import MyAppWeb.Gettext

  @display_languages ["en", "nl", "pt", "fil", "zh"]

  defmacro __using__(_) do
    quote do
      require unquote(__MODULE__)
      import unquote(__MODULE__)
    end
  end

  defmacro live_int(path, live_view) do
    for lang <- @display_languages do
      IO.inspect(path) # For example: "welcome"
      path_int = "/#{lang}/#{Gettext.with_locale(lang, fn -> dgettext("routes", path) end)}"

      quote do
        live unquote(path_int), unquote(live_view)
      end
    end
  end

  defmacro get_int(path, plug, plug_opts) do
    for lang <- @display_languages do
      path_int = "/#{lang}/#{Gettext.with_locale(lang, fn -> dgettext("routes", path) end)}"

      quote do
        live unquote(path_int), unquote(plug), unquote(plug_opts)
      end
    end
  end
end

Gettext complains that it’s not getting a string at compile-time, but instead is getting a AST node: {:path, [line: 16, column: 81], nil}. But since the path is not user generated, but defined in MyAppWeb.Router, I expected the msgid to be a string at compile-time.

Showing Posts 1 to 9

sodapopcan

sodapopcan

I’ve run into a similar thing in Ruby before. I don’t have a solid answer for you but I believe it boils down to that you need to give literal args, ie not dynamic in any way, to dgettext. These are essentially defined as identity functions that are later, uh, “processed” might be the right word? I’m not too sure how it works in Elixir, but taking a quick look at the code they all end up here. I don’t have a good grasp of when to use quote unquote: false but this is what the macro does. You can see in iex that it expand literal variable names:

iex(1)> quote(unquote: false, do: path)
{:path, [], Elixir}

So that’s likely why that is happening. I’m not sure how to work around it though you could look at a lib that does this kind of stuff (or wait until someone more knowledgable responds, lol).

On an unrelated nitpick: import does an implicit require so there is no need for both. It also makes your __using__ unnecessary!

EDIT: Just as I hit enter, @kip starts responding so ya… see what he says :smiley:

kip

kip

ex_cldr Core Team

Macros receive and return AST. Therefore path as a parameter to your macro is always going to be AST.

More specifically, I think you would need to lower the dgettext call into the quote block so that it can be expanded at the correct time with the correct parameters.

sodapopcan

sodapopcan

path in this case is a string tho so its AST should be itself, no?

kip

kip

ex_cldr Core Team

Mostly, but not always. Gettext will also accept:

iex> quote do
...> "This is" <> "a string"
...> end
{:<>, [context: Elixir, imports: [{2, Kernel}]], ["This is", "a string"]}
kip

kip

ex_cldr Core Team

Something like this is the approach I would probably take:

defmodule MyApp.Macro do
  @display_languages ["en", "nl", "pt", "fil", "zh"]

  defmacro live_int(path, live_view) do
    for lang <- @display_languages do
      quote do
        translation =
          Gettext.with_locale(unquote(lang), fn ->
            MyApp.Gettext.dgettext("routes", unquote(path))
          end)

        path_int =
          "/#{unquote(lang)}/#{translation}"

        live unquote(path_int), unquote(live_view)
      end
    end
  end
end
kip

kip

ex_cldr Core Team

I do something similar in ex_cldr_routes in the sigil_q macro - that might also give you some ideas.

LostKobrakai

LostKobrakai

No, not at all. path is a variable, so the macro receives the AST of the variable path. It doesn’t get access to the value the variable evaluates to – at runtime. And by runtime I mean when the code is executed, which in this case might still be while compiling the project.

I’ve recently written a more elaborate post, which should be a useful read:

coen.bakker

coen.bakker OP

@sodapopcan @kip @LostKobrakai

All very informative and an excellent blog post.

A minor correction on line 14, for the sake of not leaving any untied ends.

0 defmodule MyAppWeb.Macro
1    @display_languages ["en", "nl", "pt", "fil", "zh"]
2 
3   defmacro live_int(path, live_view) do
4     for lang <- @display_languages do
5       quote do
6         translation =
7           Gettext.with_locale(unquote(lang), fn ->
8             MyAppWeb.Gettext.dgettext("routes", unquote(path))
9           end)
10
11        path_int =
12           "/#{unquote(lang)}/#{translation}"
13
14        live path_int, unquote(live_view) # Make sure to not unquote `path_int`
15      end
16    end
17  end
18 end
sodapopcan

sodapopcan

Ya I don’t know what I was thinking yesterday other than my brain getting super tripped up by a problem I ran into in another language :woozy_face:

— All posts loaded —

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
Onor.io
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
jaybe78
Hello, I’m developing a online persistent chat system (what’s app) like using elixir/dynamodb/aws for a mobile app(flutter). The diffic...
New
Trolleger
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
New

Other Trending Topics Top

garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
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
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New
aseigo
ICal is a library for interacting with iCalendar data. It parses iCalendars into typed Elixir structs via ICal.from_ics, and can prepare ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews