victorstevan

victorstevan

I’m trying to use a macro to receive the module and function as atoms corresponding to equivalent modules and functions present in the faker lib. (The code below should make my intentions clear)
I’m new to Elixir and the question is not how to make it work, because it does work, but how could I make it better? I’m particularly concerned with the macro itself because the Code.eval_quoted() is giving me a bit of a code smell, but since I don’t have enough experience with the language I’m not sure how to evaluate this(the code quality and best practices).

(The maybe excessive documentation is kind of a note taking system to help with my learning)

  @typedoc """
  An uppercased atom equivalent to one of the available faker modules
  """
  @type faker_module :: atom

  @typedoc """
  A lower cased atom equivalent to a faker function whose inside a `faker_module` type
  """
  @type faker_function :: atom

  @doc """
  Given a faker module and a function (as atoms) of that module, inserts the
  module and function in a quoted expression — AST representation — and return a
  function call that could be made using the faker lib. The result should be the same
  as the call to Faker in the given module with the given function.

  ## Examples
       iex> resolve(:Address, :city)
       "Leland"
       iex> resolve(:Person, :name)
       "Darrion Emmerich MD"

  """
  @spec resolve(faker_module, faker_function) :: any
  defmacro resolve(module, function) do
    quote do
      {{:., [], [{:__aliases__, [alias: false], [:Faker, unquote(module)]}, unquote(function)]},
       [], []}
      |> Code.eval_quoted()
      |> elem(0)
    end
  end

And I’m using a mapper that looks like this

  def str_to_faker_map do
    %{
      "@id.uuid" => [:UUID, :v4],
      "@person.first_name" => [:Person, :name],
      "@geo.state" => [:Address, :state],
    }
  end

And here’s how I’m using this system to generate data based on a given JSON with this generator syntax (using “@”).

 @doc """
  Used to generate mock data for a model.
  ## Examples
      iex> model = %{
        "name" => "@person.name",
        "city" => "@geo.city",
      }
      iex> generate_data_for_model(model)
      {:ok, %{"city" => "Lake Gussie", "name" => "Hattie Schimmel"}}
  """
  @spec generate_data_for_model(model) :: {atom, map}
  def generate_data_for_model(model) when is_map(model) do
    case check_model_validity(model) do #in the code this is a private function to check if the model values are
      true ->                                                 # are in the mapper keys
        generated_model =
          for {k, v} <- model, into: %{} do
            [module, function] = map_string_to_faker_atoms(v) #Map.get on the mapper
            {k, resolve(module, function)}
          end

        {:ok, generated_model}

      _ ->
        {
          :error,
          "The model has unrepresentable values to a faker generator" <>
            "the values should have the pattern \"@module.function\"." <>
            "Notice that some modules might be remapped (ex: Address is mapped as @geo)"
        }
    end
  end

Feel free to point out any improvements I could make in any part of these snippets. This is a pet project of mine for an app that helps generate mock data.

Showing Posts 1 to 2

ityonemo

ityonemo

  1. I would say don’t use macros.
def resolve(model, fun) do
  Faker
  |> Module.concat(model)
  |> apply(fun, [])
end
  1. instead of check_model_validity(model)

why not just do Map.fetch! and let it crash if the model isn’t in there. Presumably you’re fully in control of the supplied models.

victorstevan

victorstevan OP

Thank you!

Just discovered the Module behavior and was trying to hammer it into a macro for some reason, but point 1 is definitely the way to go! Made the code a lot easier to read.

For point two, it was just an idea for handling bad requests, since this is supposed to be an API that will be consumed by a frontend that I’m building as well. But I guess you may be right and I might not need this.

— All posts loaded —

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
peck
Hi everyone. My team and I have been working on a fairly modest app based around video streaming and chat, but we’ve landed a customer t...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
bradley
I really like the adapter patterns that ecto, nebulex, waffle, etc. use and would love find something similar for a key management servic...
New
unaware8150
Hello folks! So at work, we are seeing some situations where we have to define some “fixed” strings that are used across the codebase in...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
Alvinkariuki
How Can I Optimise Compile Time Dependencies I have been building an elixir application for about 2 years now. Many modules and files ha...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
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
juhalehtonen
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews