shahryarjb

shahryarjb

Create sub module with atom name

Hello friends,
I want to create a module inside another module with an atom name:

For example:

  defmacro sub_field(name, _type, opts \\ [], do: block) do
    ast = register_struct(block, opts)

    quote do
      defmodule unquote(name) do
        unquote(ast)
      end
    end
  end

If I use Module name, it is okey and creates a sub module for me like:

sub_field(Oop, String.t(), enforce: true) do
    field(:title, String.t())
    field(:fam, String.t())
end

But If I replace Oop with :opp it has invalid module name error.

I tried to convert atom to string and use Macro.camelize() and convert it to atom again ( :Oop), but it does not accept.

Then I print :opp, it just returns :opp in my macro but if I put module name Opp it returns something like this:

{:__aliases__,
 [
   counter: {MishkaDeveloperToolsTest.GuardedStructTest.TestNestedStruct, 3},
   line: 520
 ], [:Opp]}

now how can use atom to do this?

Thank you in advance

Marked As Solved

Eiji

Eiji

Take a look at this code for inspiration:

defmodule Example do
  def sample(module) when is_atom(module) do
    module |> Atom.to_string() |> Macro.camelize() |> String.to_atom()
  end
end

module = Example

[Opp, :Opp, :opp]
|> Enum.map(&Example.sample/1)
|> Enum.map(&Module.concat(module, &1))
|> IO.inspect()

# returns: [Example.Opp, Example.Opp, Example.Opp]

Note: I have tried Module.split/1, but it does not support non-Elixir modules (those having Elixir. prefix when changing to String).

Edit: I have forgot about Macro.camelize/1, so I have updated my code. Thanks @zachallaun!

Also Liked

Eiji

Eiji

Weird… when I try this code:

defmodule MyLib do
  defmacro sub_field(name, do: block) do
    quote do
      defmodule unquote(name) do
        unquote(block)
      end
    end
  end
end

defmodule Example do
  import MyLib

  sub_field :opp do
    def sample, do: IO.inspect(__MODULE__)
  end
end

:opp.sample()

then everything is working without any problem. module is print properly and there are no warnings or errors …

zachallaun

zachallaun

On my phone, so apologies if some of this is incorrect as I can’t test it, but I’d try the following:

defmacro sub_field(name, type, opts \\ [], do: block) do
    ast = register_struct(block, opts)

    name =
      name
      |> Atom.to_string()
      |> Macro.camelize()
      |> String.to_atom()

    quote unquote: false, bind_quoted: [name: name, ast: ast] do
      module_name = Module.concat(__MODULE__, name)

      defmodule unquote(module_name) do
        unquote(ast)
      end
    end
  end

I’d really need to test to be sure, and it can be a little tricky to follow with the nested unquote/bind_quotes bit, but essentially you need to access __MODULE__ in the calling module.

Eiji

Eiji

Ah, I see … You have tried my example to create a top-level module in another module.

First of all you need to understand something … As same as you can check AST with quote do … end as same you can check how modules are “defined” inside using IO.puts(module).

iex> IO.puts(String)
Elixir.String

iex> IO.puts(Example)
Elixir.Example

iex> IO.puts(:opp)
opp

iex> IO.puts(:Opp)
Opp

With this you should understand why sub_field :Opp do … end does not generates Opp module. However it’s easy to do so. Simply add Elixir. prefix instead of :, so:

defmodule MyLib do
  defmacro sub_field(name, do: block) do
    quote do
      defmodule unquote(name) do
        unquote(block)
      end
    end
  end
end

defmodule Example do
  import MyLib

  sub_field Elixir.Opp do
    def sample, do: IO.inspect(__MODULE__)
  end
end

Opp.sample()

You can also do that within macro using for example Module.concat/2

iex> Module.concat(Elixir, :Opp)
Opp

Where Next?

Popular in Questions Top

Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
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
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

Other popular topics Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
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
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
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