Search code examples
crystal-lang

Crystal lang : `block_given` in Macro?


I want a way to detect whether a block is given to the macro, whose behaviour depends on this.

For methods, I could define two methods to handle the different situation, one with the block argument explicitly and another not. The compiler will call the correct method as expected.

But for macro, I find compiler doesn't care the polymorphism of the block argument -- it always calls the first macro whenever a block is given.


Solution

  • I'm not sure that I understood correctly, but maybe simple check help you?

    macro name(*args, &block)
      {% if block %}
        puts "with block"
      {% else %}
        puts "without block"
      {% end %}
    end
    
    name do
      "1"
    end
    #=> with block
    
    name("1")
    #=> without block
    

    https://carc.in/#/r/53yy