Ramaze Error Handling

I recently had to build custom 404 & exception handlers for a Ramaze application. There are several useful discussions on the Ramaze Google Group regarding this topic but I thought I’d synthesize the solution here for the sake of convenience.

Handling 404 Errors

Ramaze has a built-in controller action to handle 404 errors; it presents a vanilla page stating ‘No action found at: /xyz‘. Overriding this action is easy and well documented but there are a couple of things that might want to consider.

First, if you would like all 404 errors across your application to be handled by a single action, you will need to add your handling code to the base controller.

Second, using a view file corresponding to the controller action does not quite work. While the view is correctly rendered when the 404 occurs directly under a path mapped to the 404 handler’s controller (eg. /my_missing_action) it is not rendered for 404 errors occurring under paths mapped to other controllers (eg. /users/my_missing_action).

A workaround for this is to use the render_file method to manually render a view you’ve created. I have not done due diligence on this problem so I cannot tell you why it occurs – maybe it is a bug or maybe (likely) I’m missing something. If anyone has an explanation or a better work around I’d love to hear it.

Source for a Custom 404 Handler

Handling Exceptions

Routing Exceptions

Ramaze also has a built-in exception handler which presents a developer-friendly stack trace (one which I’m sure you will want to hide for the end-users). The Ramaze Google Group discussions here and here talk about how to override this default handler. It boils down to using Rack::RouteExceptions.route(exception, to); a method that takes the type of exception to route and the path of the action to route it to.

For example, to route all exceptions to the same controller you could use (as stated by Lars Olsson here):

Rack::RouteExceptions.route(Exception, MyController.r(:error))

Alternatively, to handle all IOError exceptions separately you could use:

Rack::RouteExceptions.route(IOError, MyController.r(:io_error))
Rack::RouteExceptions.route(Exception, MyController.r(:error))

Note the order of the calls to route is important. You must route the most specific exceptions first or they will be routed to more general handlers specified before them.

Unlike the 404 error handler, using a standard view file does work here.

The Exception Object

To obtain the exception object within the controller action you can call:

@error = request.env[Rack::RouteExceptions::EXCEPTION]

Source for a Custom Exception Handler

pixelstats trackingpixel

Mellow Musings by Hugo RB for Free

Perhaps not a post pertinent to the software development world but one which I hope you’ll enjoy nonetheless. My brother, Hugo RB released his debut album in late 2009 to a local audience in Port Perry, Ontario. The album consists of six original ‘folk/jazz’ songs written and performed by himself and recorded/mixed by Theo Posthumus.

While I do enjoy the album, I’ll leave its review to those less biased than myself – a segment which should grow thanks to Hugo having recently released it for free on Sound Cloud. Check it out there or hit play bellow!

Mellow Musings by Hugorb

pixelstats trackingpixel

Podcasts & Big Ideas

Lately I’ve started listening to a lot of podcasts – I’ve always enjoyed good talk radio but its never on when I want it to be and I have no control over what the topic is. For me, podcasts solve both of those problems. While I’m not going to start reviewing podcasts on a regular basis, I am going to add a links on the right to my favorite ones in the hopes that you might find something that appeals to you.

There is one podcast that I do want to single out though because its so consistently enjoyable. It is TVO’s Big Ideas, a Canadian production which presents a weekly public lecture delivered by (generally) great speakers on all sorts of topics. It is a veritable gold mine of interesting ideas, perspectives and history that I otherwise would not come across under normal circumstances. You can find more information about it here or subscribe to it here

pixelstats trackingpixel

Running Ramaze with Unicorn, Nginx and God

I’ve been meaning to write a post about running a Ramaze website under a reasonable setup for a long time now so I’m happy to finally get to it. I’m going to focus my attention on the configuration of the setup vs the installation of the software - RACKRamazeUnicorn and God are ruby gems and there are plenty of good articles about installing Nginx out there already.

What You Need

I’ve included the version number of the software I’ve tested this setup with but I suspect this configuration will work with newer versions as well (and probably older versions too).

  1. RACK (web server interface)
    • 1.0.1
  2. Unicorn (http server)
    • 0.95.2
  3. Nginx (front end reverse proxy server)
    • 0.6.36
  4. God (process monitoring)
    • 0.7.13
  5. Ramaze (web framework)
    • 2009-05

Some Assumptions

While the config files below make the following assumptions you should be able to handle any discrepancies by altering the paths or changing the run user.

  1. Nginx is configured to read configuration files from its conf/sites-enabled directory
    • Add include <path to nginx install>/conf/sites-enabled/*; to the http section of your primary Nginx config file to enable this
  2. Your website will run under the www-data user
  3. The NginxUnicorn and God config files exist within the config directory of your Ramaze website
  4. The RACK config file (config.ru) is in the root of your website
  5. You’ve created the log and tmp/pids directories underneath the root of your website

Configuring the Pieces

1. RACK

This config file is actually a very simple ruby file, its main purpose in this situation is to load your website’s app.rb via the require statement. This in turn loads the rest of your site.

3. Unicorn

While I’ve commented the major parts of the configuration file inline, I highly recommend checking out the Unicorn website and this sample configuration file for more details/features.

2. Nginx

You can find more info about configuring Nginx here. If assumptions #2 & #4 are true then you’ll need to create a symlink in the <path-to-nginx-install>/conf/sites-enabled/* directory to your Nginx config in the config directory under the root of your website. You can do this by executing

ln -s /var/www/apps/my.domain.com/config/nginx.conf <path-to-nginx-install>/conf/sites-enabled/my.domain.com

4. God

As with the RACK and Unicorn config files, this one is also written in Ruby. The God home page has a much more detailed breakdown of the config file and is definitely worth a read.

Flicking the Switch

Once you have your configuration files in place and your website on your target server you’re going to need to turn it all on. The first step is to tell God to keep an eye on your Unicorn process and the second step is to cycle Nginx forcing it to pickup your new website’s config file.

Alerting God

The first thing to do is start God and have it monitor your master Unicorn process for your new website. If God is not already running you can start it using:

god --log-level=debug

To have it start monitoring your Unicorn process, execute the following:

sudo god load /var/www/apps/my.domain.com/config/god.conf

Cycling Nginx

Cycling Nginx is something that cries out for a script so here is a simple one:

Dealing with Errors

After flicking the switch for the first time under this setup I’ve run into a 502 bad gateway error multiple times. Each time it was because I had forgotten to create the required tmp/pids or log directories under the website root. If you do run into a 502 its probably because Unicorn had trouble starting up or Nginx is not pointing to the right spot.

Debugging

Check the God logs for your website by executing:

god --log-level debug log my.domain.com

That will tell you if God has managed to start the Unicorn process successfully. If it has then checkout the Unicorn error logs in the log directory of your website. If it cannot start the process and doesn’t indicate why then try executing the Unicorn startup command in a shell directly (that should at least give you the error message Unicorn is generating).

pixelstats trackingpixel

Ramaze Partials with Etanni

Innate/Ramaze Version: 2009-10
Template Engine: Etanni

The title of this blog post is a little inaccurate as what I’m actually going to describe are Etanni partials but considering Etanni is the default template engine in Innate/Ramaze 2009-10 I figured “Ramaze Partials” was a fair generalization.

Etanni partials are easy to work with and as Pistos points out below they are documented in the rdocs. That said, when I went about looking for info on them (using Google) I missed the rdocs and could only find brief mentions of a “render helper” in the blogosphere. My hope is that this post will make it easier to find this information.

The Render Helper

This render helper can be found in the Innate code base – it is clearly commented and worth a look if you’ve got a few minutes. There are 3 methods that this helper provides to aid you in the creation of your partials:

  1. render_partial
  2. render_view
  3. render_file

I will only cover render_partial as it is the only one that I’ve needed to use thus far.

render_partial

render_partial(action_name, variables = {})

The action_name parameter references a controller method and the variables parameter is a hash which is turned into members which are locally accessible within that method. Note that action_name doesn’t have to actually have a method declaration within a controller – it can simply be the name of a view.

Example

Here is the example code for a rendering contact information via an Etanni partial:

pixelstats trackingpixel

Rails Alternatives: Merb, Sinatra & Ramaze

Over the past few months I’ve been on the hunt for a Ruby web framework to replace Rails as my weapon of choice when building an online presence. Rails struck me as being overly heavy in this context and I wanted something lighter.

I was primarily looking for a web framework that, out of the box, supported a healthy variety of template/ORM options, offered flexible routing and good layout/view support.

My search took me through the green pastures of Merb, into Sinatra’s glitzy jazz hall and finally into the land of Ramaze.

Merb’s Green Pastures

I had heard so many good things about Merb that starting with it seemed like a no brainer. The rewrite of xambr.com using Merb was mostly an enjoyable experience – Merb was able to do everything I was doing with Rails out of the box.

There were annoying holes in the documentation but nothing that couldn’t be filled in through a bit of spelunking in the code base – which was pretty clean and easy to understand (at least the parts I looked at were).

Of course, a couple days after finishing the rewrite of xambr.com I read that Merb was to be merged into Rails v3. At first I was a little dismayed but I’ve come to the opinion that the merge is a good thing – Rails will definitely benefit from it and I think Merb’s spot will be taken by the very capable, if under-appreciated, Ramaze.

I ran xambr.com on Merb for about 3 months during which time I dabbled in Sinatra (previously blogged about here). These first experiences with Sinatra were very positive and I liked the fact that it was lighter than Merb – so I figured I’d give it a shot.

Getting Classy with Sinatra [Redux]

While the rewrite of xambr.com in Merb had taken about 10 hours the rewrite in Sinatra took 1/2 that time… or at least 90% of it did.

I got hung up when trying to figure out how to have multiple view sections within a single layout (like Merb’s throw/catch system). Several hours of searching and tinkering didn’t turn anything up other than a tidbit on Github using Haml – which I was not able to get working with Erubis (and I didn’t want to switch to Haml).

Its very likely that with a bit more poking around, maybe hitting up the mailing list or IRC, a solution could have been found but I didn’t want to spend any more time with it – as mentioned above I was looking for a web framework that did all of this out of the box.

So I was a little disappointed, but I still think Sinatra is a great little web framework – just not for online presences (or at least not xambr.com).

Ramaze FTW

I stumbled upon Ramaze several months before starting this little adventure but never gave it the look it deserved. Revisiting it was the best thing I’ve done all year (code wise anyway). How can one possibly argue with “Any ruby, any adapter, any ORM and any template engine” – contortionists everywhere are jealous of Ramaze’s flexibility.

Rewriting xambr.com in Ramaze took about the same time as it did in Merb – roughly 10 hours. I started off using Erubis but ultimately ended up using Nagoro – mainly because I liked its “Page Elements” which are like partials only better. Nagoro is pretty close to Erubis but I’d say its a little more natural if you’re coming at them both with a fresh slate (due to its substitution syntax).

Ramaze has a great community too – a question I posed on the Ramaze IRC channel about some odd Nagoro behavior got an immediate, friendly response from Ramaze’s creator, Michael Fellinger. Now, I’m not a frequenter of IRC channels in general so I wouldn’t know if getting friendly answers from a technology’s creator is the norm but to me it was a much appreciated surprise (thanks Michael!).

The documentation for Ramaze isn’t quite complete but its pretty close – more so than for Merb in my opinion. That said it does seem to be less the subject of blog posts than Merb (although I think that will all change in the coming months). Its got a book (albeit an incomplete one), a ton of well written examples of ranging in size from hello world to a social networking site and a great set of blog posts by Pistos.

All my gushing aside, I did run into a bit of trouble finding a good end-to-end deployment solution. This wasn’t a bad thing though – it forced me to get to know Rack a little better and look into process monitoring solutions. In the coming days (ok maybe weeks…) I’ll be posting my solution (which involves a couple of mongrels under god’s watchful eye) – its not rocket science by any stretch of the imagination but I did run into a couple of snags…

In Short…

To sum it all up for those of you who’d rather read the back of the envelope (thats me!) here is how I’d characterize each of these Ruby web frameworks:

  • Merb
    • Skip it and check out Ramaze instead
      • Merb will likely give you a leg up on Rails 3 but Ramaze will serve you better in the “alternative to Rails” context.
  • Sinatra
    • Great place to start if you’re new to web development
      • The README page is close to a one stop shop for everything you need to get up and singing
    • The handy multi-tool you need to get small jobs done quickly
  • Ramaze
    • The fine wine of Ruby web frameworks
      • It requires a bit more work but its very rewarding
    • Fluff-less
pixelstats trackingpixel

Bridging the gap

Mike Gunderloy started off this week by announcing an exciting new initiative: Rails Bridge. Its mission statement says it all:

To create an inclusive and friendly Ruby on Rails community

To give a bit of context to my excitement… Up until this time I could sum up my view of the Rails community in one sentence:

Novices need not apply

I’m not saying community wasn’t willing to help novices, just that it didn’t seem to want the help of novices and in my eyes, the end result was that it looked very top heavy. That appearance has been enough to keep me at bay and I’m sure I’m not the only one… After all, spare time is limited and it seems like a waste to spend it simply trying to open a door.

Rails Bridge looks to change all of that and based on their group discussion they’re heading in the right direction. I’m hoping they will succeed in making the community easier to enter and in doing so open the door for many more experts-to-be.

Count me in.

pixelstats trackingpixel

Getting Classy with Sinatra

I had heard about the Sinatra Ruby web DSL a while back but I had not had a chance to play with it until a few days ago. I’m happy to say it was a highly enjoyable experience. I accomplished what I was trying to do very quickly thanks to the good documentation and intuitive interface. It is not a replacement for MVC frameworks such as Rails, Merb, Ramaze, etc but it certainly compliments them.

Sinatra Features

The Sinatra README is a great resource for getting a run down of its features and I’m not going to regurgitate it here. However, I’d like to whet your appetite with a few of the features that caught my eye when I first scoped it out.

Rides on Rack

Sinatra rides on Rack and thus supports a wide variety of handlers such as: Thin, Mongrel, Phusion Passenger, etc (a full list is available on the Rack website). It can also be used to develop Rack middleware. More information about this is available on the README. If you’re interested in Rack middleware in general, Jon Crosby gave a great intro at the Moutain West Ruby Conf 2009.

Flexible Routing

The routing in Sinatra is powerful, supporting RESTful actions, named parameters, regular expressions, splats and user agents. See the Gist bellow for an example. The README page describes these options in more detail.

View/Template Support

There are a host of template options available when using Sinatra. Currently it supports HAML, ERB, Builder and SASS and automatic layout templates (provided you give it a “layout” template to work with). Again, checkout the README page for more details.

My Impressions

What struck me while I was working with Sinatra was how light it was and how out of the way it stayed. It was only present when I needed it to do something — outside of that, it let me build what I wanted, how I wanted. If Rails is the web developer’s assembly line then Sinatra is their essential toolkit — one drives you and the other is driven by you.

While having a pre-baked MVC web framework such as Rails and Merb is great, it does lock you in to one way of thinking about web development. With Sinatra you have the freedom to dabble and experiment — and I don’t think that can ever be a bad thing.

Resources

Here are some resources that I found to be useful in my first adventure with Sinatra.

pixelstats trackingpixel

Ruby on Linux with jEdit

I recently moved from Windows to a Linux development environment and needed to find good text editor – particularly one that was (or could be made) friends with Ruby. Ideally this editor would be cross platform because, on occasion I do have to load up Windows and if possible I wanted to avoid having a different editor for each environment.

On Windows I was using E – but that does not run on Linux and I had a couple of gripes with it (slow loading of large files and overaggressive code completion). I gave Vim/gVim a shot but I didn’t enjoy text-editing in a console and gVim is ugly (yes, I do believe attractiveness is important). I was suspicious of the IDE possibilities out there but I did give a number of them (RadRails, RDE, Eclipse, etc) a quick shot. Suffice to say they all suffered from one or more of the following: being too bloated, waving too many wands and possessing play buttons (I feel a rant coming on… stifle!).

Enter jEdit. It is a very functional, customizable, extensible, java based editor and it looks pretty good to boot. So a couple weeks ago I set it up on both my Windows and Linux installs and so far so good – it has what I want and does not suffer from the gripes I had with E. One of my favourite features so far (keep in mind its only been a couple weeks) is it’s “Hyper Search” which is a bit like a built in ack.

Currently, I’m using the following plugins (geared towards ruby/web development):

  • Editor Scheme (for pre-fabricated syntax highlighting schemes)
  • RubyPlugin
  • Console
  • Templates

One thing I did have to do in order to get Ruby ERB files to be highlighted properly was to update jEdit’s “modes” catalog file. On my Windows install this was located in C:\Program Files\jEdit\Modes and on Linux it was located in /usr/share/jEdit/modes. My file already contained a reference to an ‘rhtml’ mode so I just updated it – here is the whole mode block:

  <MODE NAME="erb"		FILE="erb.xml"
				FILE_NAME_GLOB="*.{.html.erb,rhtml}" />

If you use that you’ll also need to rename the file rhtml.xml to erb.xml (it will be in the same directory as the catalog file).

As I said I’ve only been using jEdit for a couple of weeks but thus far I do not have anything negative to report. If that changes I’ll update this post. In the meantime, if anyone has any comments about jEdit or other options I might have overlooked please let me (and us) know.

pixelstats trackingpixel

WP Framework

Here is the first peak into that box of stones I mentioned on the about page.

WP Framework is a blank Word Press(WP) theme that you can use to easily setup a your own theme for your WP blog. When I started this blog I debated whether or not I wanted to spend the time putting together my own theme – do I want to spend time CSS-ing or writing? In the end I figured to give it a shot thinking that at the very least I would get a little more familiar with this blogging software.

I started by fiddling around with the default WP theme but found the results to similar to a well dressed plate having its mashed potatoes with gravy swapped out for rice – things were looking messy. So I googled around a bit and came across the concept of WP “theme frameworks”. These are basically pre-baked vanilla cakes ready for their icing to be added.

After downloading a few and taking a very quick look around I decided to give WP Framework a shot. It seemed to provide the most functional starting position without getting in the way. So a few pleasent hours later here I am with my custom theme. Thanks WP Framework.

One thing I did trip over (this isn’t directly related to WP Framework itself) was the ability to add a “home” link to the navigation bar at the top of the page. I confess to not having read any of the WP or WP Framework documentation so I cannot say whether or not it mentions how to do this (my guess is that it does). But for those of you who, like me, tend to skip the docs here is the solution (at least for WP 2.7):

There is a PHP method wp_page_menu( $args = array() ) in wp-includes/post-template.php which is used to create the navigation links. This method checks the $args array for an option called show_home. If specified it uses this option’s value for the text of the home page link and if it is not specified (the default) no home page link is displayed.

For this blog I’m calling that method using:

wp_page_menu( array('show_home'=>'Blog', 'menu_class'=>'nav') );

I hope this first peak into my box has been useful to you.

pixelstats trackingpixel