Groovy web console

subscribe to the feed Subscribe
to this
site

Hierarchical GString Tabulation

Published 5 days ago by Kirill Knyazev with tags Groovy GString Tabulation
Actions Execute script  ▶ Edit in console Back to console Show/hide line numbers View recent scripts
def put(Map opts = [:], x) {
    def y = x.toString()
    y = y.stripMargin('"') - ~/(?<=[\n\r])[^\S\n\r]+$/
    if(opts.builder)
        tab(opts.builder, y)
    else
        y
}

def tab(builder, message) {
    def b = builder.getBuilder()
    def quoteIdx = b.lastIndexOf('"')
    def spaces = (' ' * (b.length() - (quoteIdx > 0 ? quoteIdx + 1 : 0)))
    def out = put(message).replace('\n', '\n' + spaces)
    b.append(out)
}

def messageZ = put("""<
                     "<""")

def message0 = put("""--> 0#${b->put(messageZ, builder: b)}
                     "--> 1
                     "--> 2""")


def message =               put("""A
                                  " B
                                  "  C
                                  "  D
                                  " E
                                  "  [${b->put(message0, builder: b)}]
                                  "  F
                                  "   G
                                  " H
                                  """)

def data = [[name: 'foo', address: 'foo.com'],
            [name: 'bar', address: 'bar.com'],
            [name: 'baz', address: 'baz.com']]

println put("""begin
              "------------------------------
              ">>>>>>>> ${b->put(message, builder: b)}
              "------------------------------
              "<<<<<<<< ${b->put(data.join('\n'), builder: b)}
              "------------------------------
              "end
              """)
println """++++++++++++++++++++++++++++++"""

def messageZ1 = put("""<
                      "<""")

def message01 = put("""123
                      "--> 0#${b->put(messageZ1, builder: b)}
                      """)

println "${message01}"