Friday, August 9, 2013

Custom CFML BOOL() function

I needed a convenient way to get a trusted Boolean value and didn't want to be doing inline conditions repeatedly, so I write a little function called BOOL to do this:


<cffunction name="bool" access="public" returntype="boolean">
<cfargument name="in" required="No" type="any" default="" />
<cftry>
<cfreturn (arguments.in EQ "" OR arguments.in EQ false ? false : true) />
<cfcatch type="any">
<cfreturn false />
</cfcatch>
</cftry>
</cffunction>

I'm surprised Railo and Adobe don't have this as a native function. There is the old YesNoFormat() function but that throws errors on strings or anything complex. No good at all.

With Javascript, and other true scripting languages I assume, you can take nearly anything and put two exclamation marks in front if it and it's boolean: var x = 'a'; return !!x; I love the bang-bang. I use that often as well.


Also, on the above function, If you need a guaranteed 1 or 0 result you can run VAL(BOOL(variables.whatever)) and that forces true/false into 1/0.

I have a component with functions like this which I re-use on most projects, and I put it in the server scope, or application scope depending on the environment, so I can call server.bool().


That's it. Short and sweet.