Overriding a UDF in ColdFusion
This morning my friend Don asked me the question of "I have a UDF defined in Application.cfc. Is there a way to override that with a UDF of same name in another template?"
Here is the solution that I was able to come up with. It is not the most elegant thing but it worked. User defined functions are usually just stored in the in the variables scope unless you do something special. The solution was to put in some logic to detect the function, delete it, create a function with a new name and then create a pointer with the old function name to the new function name.
Application.cfm
<cfscript>
function donLooksLike(){
return "Britney Spears";
}
</cfscript>
myTemplate.cfm
#donLooksLike()#
</cfoutput>
<cfif isDefined("variables.donLooksLike")>
<cfif isCustomFunction(variables.donLooksLike)>
<cfset structDelete(variables,"donLooksLike")>
<cfscript>
function donLooksLikeTemp(){
return "ZZ Top";
}
variables.donLooksLike = variables.donLooksLikeTemp;
</cfscript>
</cfif>
</cfif>
<cfoutput>
#donLooksLike()#
</cfoutput>
If you ran the myTemplate.cfm you would see that it would first output "Britney Spears" and then "ZZ Top". Oh and by the way Don looks a lot closer to ZZ Top than Britney. He is a brilliant developer and all around great guy that knows how to rock a fedora.
There are no comments for this entry.
[Add Comment]