The Crystal Programming Language Forum

Is there a better way to use macro custom method parameters?

macro def_find(*args)
  {{ args_exp_s = args.join(", ")}}

  def find(id : Int64, {{args_exp_s.id}})
    puts "[CALLING] Find by id, conditional: {{args_exp_s.id}}"

    {{yield}}
  end
end


def_find name, age : Int32 = 18 do
  puts "Some implementation"
end

find(1, "Jake")

Output:

[CALLING] Find by id, conditional: name, age : Int32 = 18
Some implementation

My way above converts a Tuple to a String and then inserts it into the parameter definition of the method.

I want to ask if there is a ready-made way to do this?

I don’t think there’s another way to do it. But the above one seems fine (it’s just a join).

1 Like