Thursday, 31 July 2014

Cool (I think?) Railo can have dynamic case values

G'day:
Thanks to NicholasC from IRC for putting me onto this. Apparently in Railo, one can have dynamic values for case values in a switch/case!

Here's an example:

<!--- dynamicCaseInTags.cfm--->
<cfswitch expression="#URL.option#">
    <cfcase value="1">
        one
    </cfcase>
    <cfcase value="2">
        two
    </cfcase>
    <cfcase value="#URL.favourite#">
        the favourite one: <cfoutput>#URL.favourite#</cfoutput>
    </cfcase>
    <cfdefaultcase>
        the default
    </cfdefaultcase>
</cfswitch>

Occasionally I've needed to do this sort of thing, but CF has always said something along the lines of:

The following information is meant for the website developer for debugging purposes.
Error Occurred While Processing Request

Expression at line 9 has to be constant value.


Today Nicholas showed me some code he was working on, and I observed I thought it was unlikely to work as it had a dynamic value for a case. But it did work! Because he's on Railo.

Yay for Railo.

For completeness, it also works in CFScript just fine (I wondered if the parser might get confused, but no):

// dynamicCaseInScript.cfm
switch (URL.option){
    case "1":
        writeOutput("one");
    break;
    case "2":
        writeOutput("two");
    break;
    case URL.favourite:
        writeOutput("the favourite one: #URL.favourite#");
    break;
    default:
        writeOutput("the default");
    break;
}

One can even use a function for the case value:

// dynamicCaseInScriptWithFunction.cfm
switch (URL.option){
    case "1":
        writeOutput("one");
    break;
    case "2":
        writeOutput("two");
    break;
    case getThirdCase():
        writeOutput("the favourite one: #URL.favourite#");
    break;
    default:
        writeOutput("the default");
    break;
}

function getThirdCase(){
    return randRange(3,10);
}

This is not something I'd use every day, but I have definitely needed it a few times in the past. And it's food for thought as to how I can leverage this functionality now that I know about it!

I've put in an enhancement request for ColdFusion: 3799027.

Righto.

--
Adam