views:

51

answers:

1

Use Case: Take an HTML file with comments in a specific format (a format I specified), and change it to a JSP page that fills in these special areas with custom JSP code.

Simple Example:

<html>
<!-- start:custom-title-content -->
<h1>this is the generic title content used to develop the HTML page</h1>
<!-- end:custom-title-content -->
</html>

renders:

<html>
${someMap['custom-title-content']}
</html>

Now, I've already solved this problem, but can't help feeling that I've left some of the scripting language power on the table. Please review my script and critique.

File folder = new File(/C:\wamp\www\preview/)
File f = new File(folder, /index.html/)
assert f.exists()

//create result so string can be changed while iterating through
def text = f.getText()
def result = f.getText()

//regex to pull section names
def names = text =~ /(?ms)<!-- ?start:((\w+|-)+) ?-->/

//for each matched section name
names = names.each {
    //match regex from begining of tag to end of tag
    def sectionMatcher = text =~ /(?ms)<!-- ?start:(/ + it[1] + /) ?-->.*<!-- ?end:(/ + it[1] + /) ?-->/
    def section = sectionMatcher[0][0] // the whole section to be replaced
    def label = sectionMatcher[0][1] // the name of the value to be replaced with
    def replacementTag = """\${templateMap['${label}']}""" // the tag needed map key
    result = result.replace(section, replacementTag) // replace section
}

new File(folder, f.getName() + ".replaced") << result //store result in new file
A: 

You could do it this way, using the *. operator to get at the tagnames in the names array, then inject to repeatedly alter a single string (that you get from the file)

File folder = new File(/C:\wamp\www\preview/)
File f = new File(folder, /index.html/)
assert f.exists()

//load the template file
def text = f.getText()

//regex to pull section names
def names = text =~ /(?ms)<!-- ?start:((\w+|-)+) ?-->/

//for each matched section name, do the replacement, and store the final string in result
def result = names*.getAt( 1 ).inject( text ) { currentTxt, tag ->
  def sectionMatcher = currentTxt =~ "(?ms)<!-- ?start:($tag) ?-->.*<!-- ?end:($tag) ?-->"
  currentTxt.replace( sectionMatcher[0][0], "\${templateMap['$tag']}" ) // replace section
}

new File(folder, f.getName() + ".replaced") << result //store result in new file

It's arguably less clear than your version though ;-)

tim_yates