Brail's Extension Methods

time to read 8 min | 1508 words

On Castle Dev, Chris has asked the following question, how can you build the common "empty" template with Brail? NVelocity makes it very easy:

#foreach $item in $items




      No Data!


But Brail makes it more cumbersome. There are solutions using view components, but they are too much, all too often. So, can we find an elegant solution to the problem?

As it turn out, yes (otherwise I probably wouldn't write this post :-) ). Brail is based on Boo, and Boo has extension methods... Another concept that Brail has is "Common Scripts", a set of helper methods that can be used across all the views in the application. Here is the script that I put in /Views/CommonScripts/extensions.brail:


static def IsEmpty(val as object) as bool:

      if val isa System.Collections.ICollection:

            return cast(System.Collections.ICollection,val).Count == 0


      return true


Now you have extended all the objects in the application, so we can use it like this:


    for item in items:

        output item


    output "No Data" if items.IsEmpty


I like that :-) The notion can be extended to more complex issues, naturally, such as ToXml extension method, etc. In fact, you can even forward calls to C# code, so that makes it even more powerful (I assume (and suggest against) that you aren't going to write a lot of code in the extensions).