How to check if a constant is defined in Crystal

I need to check if a constant is defined to fulfill the condition.

I tried this, but the “specific” method does not exist in this language:

if defined(constant) value = :foo else value = :bar end 
+5
source share
1 answer

Can you use macro and TypeNode # has_constant? :

 FOO = 1 value = nil {% if @type.has_constant? "FOO" %} value = :foo {% else %} value = :bar {% end %} pp value #=> :foo 

Or even better, you can write a short custom macro for this:

 macro toplevel_constant_defined?(c) {{ @type.has_constant? c }} end pp toplevel_constant_defined? "FOO" # => true pp toplevel_constant_defined? "BAR" # => false 

Note: as mentioned in Jonne Haß , you only need this in advanced macro programming, wherever there is a huge smell of code, regardless of the language used.

+5
source

Source: https://habr.com/ru/post/1271277/


All Articles