Modal dialog windows for JavaScript

Carefully implemented, modal dialog windows can dramatically improve a user interface. There are a number of libraries which offer such a system, but many have fundamental differences in design, or require certain external JS libraries, and finding the right one for me has proven a bit challenging.

My requirements: compatibility with JQuery, and importantly, the ability to degrade gracefully for those users who disable javascript. Unfortunately, this last point is where Thickbox, otherwise the leading candidate for JQuery, falls down.

The solution could well be iBox. Independent of all external javascript libraries, it is nevertheless lightweight (7kb compressed), works first time out of the box - no pun intended - and since it doesn’t hijack the HREF tag, it degrades as nicely as you could wish for.

http://www.ibegin.com/labs/ibox/

Extending restful_authentication

Most websites need to offer users several levels of access. Sometimes it’s as simple as a straight choice between logged in, or logged out - something which both restful_authentication and acts_as_authenticated handle competently.

As a site grows, however, so does the likelihood that further levels of authentication will need to be checked. Now, there’s an entire industry dedicated to solving this problem - but here’s a simple and logical way of utilizing some of restful_authentication’s methods to implement such a system. I haven’t tested this in acts_as_authenticated - but as far as I know it should work fine there too.

Firstly, we need to duplicate restful_authentication’s login_required method, in order to handle a new level of user. As an example, we’ll write a method contributor_required, which will act as a filter to ensure a given set of actions are only available to one of a website’s contributors. (I am assuming the existence of a method or two, but these should be pretty self-explanatory.)

class ApplicationController < ActionController::Base
  include AuthenticatedSystem
  ...

  protected

  def contributor_required
    login_required

    if not current_user.is_contributor?
      store_location
      flash[:notice] = "You must be a contributor to enter here!"
      redirect_to new_user_contributor_path(current_user)   # or, send wherever your app requires
      return false
    else
      return true
    end
  end
end

There are a couple of important things to note here. The first line of the method calls restful_authentication’s own login_required method. This could almost be viewed as a ’super’ method: we are assuming that in order to be a contributor, you must already be registered user - and if you’re not, you will be redirected to the basic login/register pages at this point.

Any deeper levels of user we want to create later - senior_contributor, perhaps - should therefore call contributor_required in place of login_required. This method will then itself ‘work up the chain’ and eventually end up calling login_required. We could construct an arbitrarily-sized ‘tree’ of authentication in this manner - mirroring many real-life authentication needs.

One further plus point is that the check for login_required ensures we can rely on the validity of current_user a little later on.

The other thing to notice is that - if the assumed is_contributor? method returns false - we call restful_authentication’s store_location method. This is a simple method which stores the requested URI in the session, allowing access to it later. It means we should be able to redirect back to the requested page, if we can approve the user’s contributor status.

So, all that is left is to utilize the code in our controller, where contributor_required can be used alongside login_required. Also, the use of the usual redirect_back_or_default method means we should be redirected back here after we’ve registered the user as a contributor, or whatever we need to do.

class ContributionsController
  before_filter :login_required, :only => [ :index, :show ]
  before_filter :contributor_required, :only => [ :new, :create, :edit, :update, :destroy ]

  ...

  def create
    ...
    respond_to do |format|
      format.html { redirect_back_or_default( contributions_path(@contribution) ) }
      ...
    end
  end
end

And voila! Simple, but potentially powerful role-based authentication for Rails.

Haml scaffolding for Rails

Haml is a masterstroke - since moving over to it, writing markup has ceased being the chore it was. In fact, it’s so logical and intuitive, and saves so much time, I often wonder how I coped without for so long.

The one irritation is that Rails does not yet support Haml in its scaffold generator, and new views and layouts have to be manually converted each time.

I have found two solutions to this, so far: firstly, Daniel Fischer’s haml generator kills two birds with one stone, by also including support for generating relevant RSpec testing configuration files. A brief testing has revealed no obvious problems.

Secondly, James Golick’s resource_controller claims to do a similar job, although I am yet to test this at the time of writing.

Next on my wishlist: An automatic ERB <-> Haml converter.

Object.too_clever_by_half? rescue nil

Monkey-patching proposals have abounded in the Ruby community recently - including, but not limited to Object#andand, Object#_? and SafeNil and Object#method_.

The underlying aim of all seems to be to keep code as DRY as possible. Inline validity checking is considered too ugly and verbose, as in the following snippet:

@person.name unless @person.nil?

Most of the proposals, however, make no mention of Ruby’s exception handling routines. These routines are designed for the very purpose of removing unpleasant and repetitive error-handling procedures from code, and could be readily utilized in most or all the examples I have seen.

Ruby’s dynamic language features are powerful and alluring: but I believe that altering the fundamental behaviour of NilClass, as some have suggested, should be avoided wherever possible - and that probably means always.

Or to put it another way: When does DRY become more important than KISS?

Shifting paradigms

Anand Rajaraman describes a group of students eschewing complicated movie data-mining algorithms in favour of a simple, effective alternative tactic: comparing their data with additional information from the IMDB website.

In the same post, he compares this with Google’s great leap forward in the late nineties: the inclusion of hyperlink counts and anchor text recognition in their search engine results, which helped put them firmly one step ahead of the competition.

He sums it up thus:

… if you have limited resources, add more data rather than fine-tuning the weights on your fancy machine-learning algorithm.

I would go a step further. Both of these are perfect examples of how the biggest leaps forward usually come from a paradigm shift, a fundamental change in thinking - a change which is often profoundly simpler than the alternatives, but paradoxically, much harder to see.

On the problem of configuring a server.

Building a server from scratch is hardly trivial, and I’m far from an expert in the finer points of the art. And since the implications of getting it wrong don’t bear considering for too long, getting the right information is crucial. Enter Slicehost’s series of in-depth tutorials.

I heartily applaud the philosophy of gentle guidance which deliberately stops short of trying to define a one-size-fits-all configuration for every circumstance. It is left to the reader to weigh up the possible options and make his own decision - but the information presented is first-class, with a strong emphasis on security which sometimes seems to be lacking in many other articles.

As if that wasn’t enough, there are even multiple versions of each tutorial, tailored to different Linux distributions.

Automate your database content migrations

Rails manages database schema migrations with the minimum of fuss, but the prospect of copying database content between a number of development and deployment machines has long filled me with a faint sense of dread.

Usually, I have resorted to the cumbersome process of producing and tarball-ing an SQL dump of the data, transferring it to the new machine, booting up mysql, importing the data… it’s lengthy, tiresome and error-prone.

Despite toying with the idea of writing a rake task to automate the process many times, I’ve never quite got it together. So I’m happy to come across this plugin. It’s not quite brand new - but it works well, and better still it’s database independent, which means you can switch your entire DB from say, MySQL to Postgres and back with ease.

http://blog.heroku.com/archives/2007/11/23/yamldb_for_databaseindependent_data_dumps/

And, so…

An experiment writing a blog! As with most decisions I make, I will err on the side of my own experience. I read blogs only for reasons related to coding; usually when struggling with problems of which others have been thoughtful enough to share their knowledge. And to a slightly lesser extent, to inform me about wider trends and philosophies, and keep up-to-date with new tools and technologies which are of interest, or use to me.

So, this blog will follow a similar schema. I intend to write about the tools I use, and problems I face, in my working life: currently relating to the Ruby programming language and the Ruby on Rails web-application framework. I suspect that Javascript, AJAX, databases, other development tools, and some wider programming topics will be candidates for inclusion.

And academically, I’m mainly focussed on the real-time audio synthesis language, SuperCollider - a powerful and beautifully crafted language which shares a Smalltalk ancestry with Ruby, and provides me with a gateway into live digital signal processing. Other open source DSP software, as well as more mainstream music production software and hardware, is also of interest to me, and could merit a mention in due course.

So, the ground has been set!

Hello world

new blog post

… testing 123