英文:
"application.get_key > modules" will return :undefined
问题
I want to get a list of the modules in a certain namespace at the compile time, as a macro.
defmodule MyApp.MyModuleLoader do
defmacro __using__(opts) do
quote bind_quoted: [opts: opts] do
a1 = :application.get_key(:my_app)
modules = :application.get_key(:my_app, :modules)
IO.puts("****:a1: #{Kernel.inspect(a1)}")
IO.puts("****:modules: #{Kernel.inspect(modules)}")
# ===> :undefined
# filter out the ones I don't need...
# ....
end
end
end
I'll then use MyModuleLoader
in a schema-model module. But it'll print out :undefined
for both variables during compilation.
Why? How to fix this?
英文:
I want to get a list of the modules in a certain namespace at the compile time, as a macro.
defmodule MyApp.MyModuleLoader do
defmacro __using__(opts) do
quote bind_quoted: [opts: opts] do
a1 = :application.get_key(:my_app)
modules = :application.get_key(:my_app, :modules)
IO.puts("****:a1: #{Kernel.inspect(a1)}")
IO.puts("****:modules: #{Kernel.inspect(modules)}")
# ====> :undefined
# filter out the ones I don't need...
# ....
end
end
end
I'll then use MyModuleLoader
in a schema-model module.
But it'll print out :undefined
for both variables during compilation.
Why? How to fix this?
答案1
得分: 1
If we add Application.ensure_loaded(:my_app)
like:
defmodule MyApp.MyModuleLoader do
defmacro __using__(opts) do
quote bind_quoted: [opts: opts] do
Application.ensure_loaded(:my_app) # <-
a1 = :application.get_key(:my_app)
modules = :application.get_key(:my_app, :modules)
IO.puts("****:a1: #{Kernel.inspect(a1)}")
IO.puts("****:modules: #{Kernel.inspect(modules)}")
# ===> :undefined
# filter out the ones I don't need...
# ....
end
end
end
Then the output (ran via iex -S mix
) will be:
****:a1: :undefined
****:modules: {:ok, [<list of modules>]}
After changing IO.puts(...)
to IO.inspect(...)
we get the same output from mix compile
command.
英文:
If we add Application.ensure_loaded(:my_app)
like:
defmodule MyApp.MyModuleLoader do
defmacro __using__(opts) do
quote bind_quoted: [opts: opts] do
Application.ensure_loaded(:my_app) # <-
a1 = :application.get_key(:my_app)
modules = :application.get_key(:my_app, :modules)
IO.puts("****:a1: #{Kernel.inspect(a1)}")
IO.puts("****:modules: #{Kernel.inspect(modules)}")
# ====> :undefined
# filter out the ones I don't need...
# ....
end
end
end
Then the output (ran via iex -S mix
) will be:
****:a1: :undefined
****:modules: {:ok, [<list of modules>]}
After changing IO.puts(...)
to IO.inspect(...)
we get the same output from mix compile
command.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论