shahryarjb

shahryarjb

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

Showing Posts 1 to 10

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 …

shahryarjb

shahryarjb OP

Hello @Eiji, you could not be able to create something Opp.sample() ?

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 OP

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

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

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!

zachallaun

zachallaun

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

Eiji

Eiji

right, my bad :sweat_smile:

shahryarjb

shahryarjb OP

I have this eror for this:

error: unquote called outside quote
  test/guarded_struct_test.exs:521: MishkaDeveloperToolsTest.GuardedStructTest.TestNestedStruct (module)
shahryarjb

shahryarjb OP

Yes this place we can concat the module!! but when I use this inside my macro it does not work and has error.

  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

Error

➜  mishka_developer_tools git:(master) ✗ mix test
Compiling 1 file (.ex)
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


== Compilation error in file test/guarded_struct_test.exs ==
** (CompileError) test/guarded_struct_test.exs: cannot compile module MishkaDeveloperToolsTest.GuardedStructTest (errors have been logged)
    (stdlib 5.0.2) lists.erl:1706: :lists.mapfoldl_1/3
    (stdlib 5.0.2) lists.erl:1706: :lists.mapfoldl_1/3
    (ex_unit 1.15.1) expanding macro: ExUnit.Assertions.assert/1
    test/guarded_struct_test.exs:534: MishkaDeveloperToolsTest.GuardedStructTest."test nested macro field"/1

Where Next? Top

Trending in Questions Top

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
RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
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
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

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
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & 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

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews