IronRuby and ASP.NET MVC
At Tech Ed last week, I showed a prototype of integration between IronRuby and ASP.NET MVC. I was really happy about how straightforward this turned out to be; it’s a strong testament to the robustness of our hosting API that Levi on the ASP.NET MVC team was able to add IronRuby integration with only a simple example and the existing docs.
Let’s walk through a simple example. Keep in mind that this is a prototype, and that many things will likely change before we’re done with it (particularly some of things we do today with globals and instance variables).
First, let’s look at how you can define some default routes via routes.rb:
Next, let’s look at the Controller code for the HomeController:
The index action renders a view using a trivial Model which lives in models\HomeModel.rb:
This model is used by the index action View, which lives in views\home\index.rhtml:
Next, let's look at a slightly more sophisticated example using a Products Controller that renders a list of categories that looks like:
It also renders a list products for a category when you click on it:
This is what the controller looks like:
There are two actions in this controller: index and list. The index action returns a list of the categories, and the list action returns a list of products for that category.
Note that we're using instance variables on the controller to communicate with the view - this is likely going to change in the future, but it was something we hacked in to see what it would look like.
If we look at ProductsModel, you'll see that it contains a simple adapter around a Visual Studio generated wrapper for the Northwind database:
We had to write our own adapter to work around a few bugs that we have in our .NET interop story as of right now, as well as adding a few model-esque methods. Here's what the NorthwindDatabase adapter looks like:
Notice how we can use LINQ to SQL to write our queries to the database, and the funky C# 3.0 anonymous delegate syntax that we use for GetCategory().
The interesting code in the view looks like:
Today we're using the MVC template engine, but there isn't any reason why we couldn't enable erb / haml etc. in the future.
How can I get it?
You can download a ZIP of the entire project from here if you want to take a closer look. Note that you can't run these bits yet, since I demo'd it using a private build of ASP.NET MVC from mid-way through their current milestone. That said, when Preview 4 of ASP.NET MVC ships you'll be able to run IronRuby on top of it (their current release is Preview 3).
Look for a blog post here, and from the folks like Phil over in MVC-land when we're ready to ship you some bits to build MVC apps using IronRuby.
Recent Comments