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
shahryarjb

shahryarjb

Thank you for the time you explain this, but I need to convert atom inside sub_field macro, and user just put an atom

Code:

  defmodule TestNestedStruct do
    use GuardedStruct

    guardedstruct do
      field(:title, String.t())
      field(:subject, String.t())

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

      field(:site, String.t())
    end
  end

And

Error

error: MishkaDeveloperToolsTest.GuardedStructTest.TestNestedStruct.Oop.__struct__/0 is undefined, cannot expand struct MishkaDeveloperToolsTest.GuardedStructTest.TestNestedStruct.Oop. Make sure the struct name is correct. If the struct name exists and is correct but it still cannot be found, you likely have cyclic module usage in your code
  test/guarded_struct_test.exs:534: MishkaDeveloperToolsTest.GuardedStructTest."test nested macro field"/1

I think it just accept a Tuple for creating submodule

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

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

    module_name = Module.concat(Elixir, name)

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

If I put sub_field(Oop, String.t(), enforce: true) do, it works :frowning:

I am improving my macro

zachallaun

zachallaun

Credit where it’s due: I just copied it from @shahryarjb’s post above mine!

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
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
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
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
Mooodi
Given a string, how can I get access to its character by index? Enum.at("my_string", 2) doesn't work. Or rather, not char, but a substr...
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
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
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
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
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
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
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
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
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
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

We're in Beta

About us Mission Statement