Friday 17 May 2013

Enhancement to replace() in Railo 4.1

G'day:
Gert Franz has just given a very impressive presentation on some new features Railo has added in 4.0 and 4.1. There's too many to go through, but here's one that interested me.

In Railo, the replace() function can now take a struct containing key/value pairs which represent the substitution tokens / values to replace. EG:


original = "tahi, two, toru, four";
tokens = {two="rua", four="wha"};

result = replace(original, tokens);

dump(variables);

Output:
Scope
ORIGINAL
stringtahi, two, toru, four
RESULT
stringtahi, rua, toru, wha
TOKENS
Struct
four
stringwha
two
stringrua

See how both "two" and "four" have been replaced with "rua" and "wha". Nice. Simple... not earthshattering... but just nice.

One slightly cool thing here is that one can do this:

original = "tahi";

tokens = {
    "tahi" = "rua",
    "rua" = "toru"
};

result = replace(original, tokens);
dump(variables);

Scope
ORIGINAL
stringtahi
RESULT
stringtoru
TOKENS
Struct
rua
stringtoru
tahi
stringrua

So here I first replace "tahi" with "rua", then I replace "rua" with "toru". Cool.

The astute might notice that the fact that this works is more coincidence that good planning. The tokens are a struct, so they ought to be - intrinsically - unordered. So in reality it's just luck that the tahi=>rua replacement takes place before the rua=>toru one: I'm relying on an ordering in the data which isn't there.

I can't help but think the correct implementation here ought to be an array of structs, so the order can be preserved, eg:

tokens = [
    {"tahi" = "rua"},
    {"rua" = "toru"}
];

On the other hand, I happen to be sitting next to Alex Skinner as I type this, and he points out he's raised an enhancement request with Railo to add a function structListNew(), which returns an implementation of a struct which respects the ordering of the keys. That would be the best fit for the tokens data structure here. Railo haven't addressed that E/R yet though.

So not perfect, but this is a bloody handy language enhancement. Nice one Railo.

--
Adam