매크로 메서드

매크로 메서드 (Macro methods)

매크로 def는 클래스 계층을 위한 메서드를 정의하고, 각 구체 하위 타입에 대해 인스턴스화되게 해줘요.

def@type를 참조하는 매크로 표현식을 포함하면 암시적으로 macro def로 간주돼요. 예를 들어:

class Object
  def instance_vars_names
    {{ @type.instance_vars.map &.name.stringify }}
  end
end

class Person
  def initialize(@name : String, @age : Int32)
  end
end

person = Person.new "John", 30
person.instance_vars_names # => ["name", "age"]

매크로 정의에서는 인자가 AST 노드로 전달되어 매크로 확장({{some_macro_argument}})에서 접근할 수 있어요. 하지만 매크로 def에서는 그렇지 않아요. 매크로 def에서는 파라미터 목록이 매크로 def가 생성한 메서드의 파라미터 목록이에요. 컴파일 타임에는 호출 인자에 접근할 수 없어요.

class Object
  def has_instance_var?(name) : Bool
    # We cannot access name inside the macro expansion here,
    # instead we need to use the macro language to construct an array
    # and do the inclusion check at runtime.
    {{ @type.instance_vars.map &.name.stringify }}.includes? name
  end
end

person = Person.new "John", 30
person.has_instance_var?("name")     # => true
person.has_instance_var?("birthday") # => false

출처: Crystal 공식 문서

더 알아보기 (Learn more)