Skip to content

Instantly share code, notes, and snippets.

@uehaj
Created January 18, 2013 08:44
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uehaj/4563201 to your computer and use it in GitHub Desktop.
Save uehaj/4563201 to your computer and use it in GitHub Desktop.
@DelegatesToを使った静的型チェックされるMarkupBuilderのようなものです。
import groovy.transform.*
class HtmlBuilder {
def html(@DelegatesTo(Html) Closure c) {
c.delegate = new Html()
println "<html>"; c(); println "</html>"
}
}
class Html {
def head(@DelegatesTo(Head) Closure c) {
c.delegate = new Head()
println " <head>"; c(); println " </head>"
}
def body(@DelegatesTo(Body) Closure c) {
c.delegate = new Body()
println " <body>"; c(); println " </body>"
}
}
class Head {
def title(String s) { println " <title>$s</title>" }
}
class Body {
def h1(String s) { println " <h1>$s</h1>" }
def p(String s) { println " <p>$s</p>" }
def ul(@DelegatesTo(Ul) Closure c) {
c.delegate = new Ul()
println " <ul>"; c(); println " </ul>"
}
}
class Ul {
def li(String s){ println " <li>$s</li>" }
}
@TypeChecked
def test() {
new HtmlBuilder().html {
head {
title "Groovy 2.0.1は凄い!"
}
body {
p "Groovy 2.0.1は凄い!"
ul {
li "リスト1"
li "リスト2"
}
h1 "凄いわ!"
}
}
}
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment