cjbottaro

cjbottaro

Getting a list of "tagged" modules

Easiest to ask this in code…

defmodule Foo do
  use Tagger
  tag(:red)
end

defmodule Bar do
  use Tagger
  tag(:blue)
end

Then at runtime I want to be able to say:

Tagger.all_tagged # %{ Foo => :red, Bar => :blue }

How to define Tagger to do this? I know how to use module attributes and macros to create methods on Foo and Bar to keep track of what they are tagged with, but how to aggregate that info into another module?

Thanks for the help.

Marked As Solved

voltone

voltone

I would probably use module attributes to store the tag in the compiled module:

defmodule Tagger do

  defmacro __using__([]) do
    quote do
      Module.register_attribute(__MODULE__, :tag, persist: true)
    end
  end

end

defmodule Foo do
  use Tagger
  @tag :red
end 

You can then inspect the attributes using module_info/1:

iex(1)> Foo.module_info(:attributes)[:tag]
[:red]

Given a list of modules you can then simply map, filter, aggregate, etc. using Enum.

As for the list of modules, you can use {:ok, modules} = :application.get_key(:my_app, :modules) to get all modules for your OTP app. Or, if you want to scan for modules more broadly, you can look at iex’s autocomplete for inspiration:
https://github.com/elixir-lang/elixir/blob/master/lib/iex/lib/iex/autocomplete.ex#L247

Also Liked

OvermindDL1

OvermindDL1

It works for any code that is indeed loaded. It is considered loaded when some function on the module is called, until that point it is not loaded (unless the erlang compiler option in the boot forces loads everything in the one file). Your modules will appear once you call something on them.

An application is loaded by the boot loader, but again that gets back into manual plugin definitions instead of dynamic detection. ^.^

voltone

voltone

If you look closely you’ll see that the IEx code only relies on :code.all_loaded() alone when :code.get_mode() returns anything other than :interactive.

When you start your application as part of a release, the :embedded mode is used, and all modules included in the release a loaded right after the VM has started. On the other hand, when you run iex on your Mix project, the code server uses :interactive mode in which modules are located and loaded on-demand, as @OvermindDL1 described.

As for application loading, iex -S mix loads your main application and all its dependencies (actually, it first loads the dependencies and then the main app). Some dependencies may explicitly load/start additional applications as they initialize.

RomanKotov

RomanKotov

Elxir Protocols have an interesting reflection feature. It looks like SomeProtocol.__protocol__(:impls) and can return a {:consolidated, modules}. It shows all modules, that implement the protocol. You can use this to tag modules, like:

defprotocol TagExample.Tagged do
  @spec tags(t()) :: [atom()]
  def tags(data)
end

defmodule TagExample.Tag do
  alias TagExample.Tagged

  defmacro __using__(_opts) do
    quote do
      Module.register_attribute(
        __MODULE__,
        :tag,
        persist: true,
        accumulate: true
      )

      defimpl TagExample.Tagged do
        def tags(_) do
          :attributes
          |> @for.__info__()
          |> Keyword.get(:tag, [])
        end
      end
    end
  end

  defimpl Tagged, for: Atom do
    def tags(module) do
      :attributes
      |> module.__info__()
      |> Keyword.get(:tag, [])
    end
  end

  @spec tagged_modules() :: [module()]
  def tagged_modules do
    modules =
      case Tagged.__protocol__(:impls) do
        {:consolidated, modules} ->
          modules

        _ ->
          Protocol.extract_impls(
            Tagged,
            :code.lib_dir()
          )
      end

    for module <- modules,
        module.__info__(:attributes)
        |> Keyword.has_key?(:tag),
        do: module
  end

  @spec modules_with_tag(tag :: atom()) :: [module()]
  def modules_with_tag(tag) do
    for module <- tagged_modules(),
        module
        |> Tagged.tags()
        |> Enum.member?(tag),
        do: module
  end
end

defmodule TagExample.TaggedModule1 do
  use TagExample.Tag

  @tag :tag1
  @tag :tag2
end

defmodule TagExample.TaggedModule2 do
  use TagExample.Tag

  @tag :tag2
  @tag :tag3
end

# iex> TagExample.Tag.tagged_modules()
# [TagExample.TaggedModule2, TagExample.TaggedModule1]

# iex> TagExample.Tag.modules_with_tag(:tag2)
# [TagExample.TaggedModule2]

# iex> TagExample.Tag.modules_with_tag(:nonexisting_tag)
# []

This example uses module attributes, but you can store tags somewhere else (possibly in methods).

I have also created a blog post with edge cases for this implementation.

cjbottaro

cjbottaro

Oh wow. A lot more complicated than I thought, but this solves it! Thanks a ton!

cjbottaro

cjbottaro

Just for posterity, the :code.all_loaded() technique didn’t work for me. I’m not sure what marks a module as “loaded”, but when I started an iex console and called :code.all_loaded(), my modules didn’t show up in the list.

Here’s what I did instead:

Enum.each :application.loaded_applications(), fn {app, _, _} ->
  {:ok, modules} = :application.get_key(app, :modules)
  Enum.each modules, fn mod ->
    # Do my thing with mod
  end
end

Now what marks an application as loaded? I have no idea. But :application.loaded_applications() seems to return all applications in my mix project… at least at the point where I’m calling it (which is the mod: [] callback).

Where Next?

Popular in Questions Top

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
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
Kagamiiiii
Student &amp; New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
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

Other popular topics Top

dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
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
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
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
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

We're in Beta

About us Mission Statement