Parse constant from enviroment - macro parameter string interpolation

I have some global constants which I want to read from ENV or define with a default value.

I pass a parameter to the macro and want to put it into a string in the output expression.

When I use "$($name)" then I get "$(VALUE)"
When I use "$(name)" then I get "$(name)"
I want to to get back "VALUE"


Define constant directly:

const CONST1 = UInt16(10)

Parse value from ENV or default from code:

const CONST2 = parse(UInt16, get(ENV, "CONST2", "20"))

Automate using macro - can’t get it to work…

macro const_from_env(const_name::Symbol, const_type::Symbol, default_value)
    ex = quote
        const $(const_name) = parse($(const_type),
            get(ENV, "$($const_name)", "$($default_value)"))
    end
    @show ex
    esc(ex)
end

@const_from_env CONST3 UInt16 30

actual output:

ex = quote
    const CONST3 = parse(UInt16, get(ENV, "$(const_name)", "$(30)"))
end
ERROR: LoadError: UndefVarError: const_name not defined

desired output:

ex = quote
    const CONST3 = parse(UInt16, get(ENV, "CONST3", "30"))
end

I think you need $$ rather than $ and

quote quote … end end

See
https://docs.julialang.org/en/v1/manual/metaprogramming/#Nested-quote

quote quote
        const $(const_name) = parse($(const_type),
            get(ENV, "$$const_name", "$$default_value"))
    end end

gives error
ERROR: LoadError: syntax: invalid interpolation syntax: "$$"

The solution is $("$name").

Full code:

macro const_from_env(const_name::Symbol, const_type::Symbol, default_value)
    esc(quote
        const $(const_name) = parse($(const_type),
            get(ENV, $("$const_name"), $("$default_value")))
    end)
end

@const_from_env CONST3 UInt16 30
@assert 30 == CONST3