Search code examples
crystal-lang

How to see if a constant/TypeNode has been defined during a compile time macro?


Is it possible to check if a global constant (e.g. a TypeNode of Class, Struct, Module) has been defined by using a macro?

{% if defined?(::My_Class) %}
  puts "My_Class has been defined."
{% end %}

I know it's possible to get use TypeNode#has_constant?, but the question has to do whether or not a constant has been defined in the global namespace.

(The reason I asked is because during development and refactoring, I found this would be a convenient placeholder for a few circumstances until I can get the rest of the codebase re-written.)


Solution

  • In the top level scope, the macro variable @type refers to the program. You can use @type.has_constant?(:Foo) to determine if a top level constant Foo is defined.