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

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
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
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
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
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
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
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
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
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
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

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews