Brail's Extension Methods
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
#each
$item
#nodata
No Data!
#end
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:
[Boo.Lang.ExtensionAttribute]
static def IsEmpty(val as object) as bool:
if val isa System.Collections.ICollection:
return cast(System.Collections.ICollection,val).Count == 0
end
return true
end
Now you have extended all the objects in the application, so we can use it like this:
<%
for item in items:
output item
end
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).
Comments
Now that I finally got all my views converted to brail I got around to really trying this out and would suggest a couple of changes.
Add the () to the end of the if items.IsEmtpy call, that one took me a while to realize since I'm not overly familiar with boo syntax.
Instead of checking for collections I'd do
[Boo.Lang.ExtensionAttribute]
static def IsEmpty(val as duck) as bool:
end
Because checking for IEnumerable of * was not working very well for me.
Comment preview