3.7. Nesting Scripts: Calling Scripts from Scripts

To properly structure larger scripts it can be helpful to spread functionality over several scripts. The above mentioned scriptService provides simple helper methods to call scripts from within scripts. For this, consider the following script which does nothing but provide two methods

def encrypt(plaintext, k){
	plaintext?.replaceAll("[^a-zA-Z ]", "").toUpperCase().collect{
      int c = ((it == ' ' ? 0 : (((int)it) - 64)) + k) 
      if(c == 0)
      	return ' '
      return (c + 64) as char
	}.join()
} 

def decrypt(ciphertext, k){
	return encrypt(ciphertext, (27 - k) 
}

Assume this is stored in a file called lib.rs. For the interested reader, this is a simple implementation of the Caesar cipher (which should not be used for actual encryption). Now, to load these helper methods we can use the following, which we store in a file called encryptionTest.rs

GLOBALS.exec("lib.rs")

def plain = "The quick brown fox jumps over the lazy dog"
def key = 6
def cipher = encrypt(plain, key)

tout.println(plain)
tout.println(cipher)
tout.println(dec(cipher, key))

If you now run this script you should get the following output

reportserver$ exec encryptionTest.rs
The quick brown fox jumps over the lazy dog
ZNKFW OIQFHXUBTFLUCFP SVYFUAKXFZNKFRGEDFJUM
THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG

Besides the simple exec method that we have used above the GLOBALS object provides a second exec method that takes as second parameter an argument string that is passed to the script.