Don’t Rethrow, Please

Dear fellow Ruby developers, please kick the habit of catching  and rethrowing exceptions, thus ridding your users of the expeptions’ stack traces. Recently I had to patch the source code of an ActiveRecord adapter as well as the underlying DBI implementation in order to find out where one particular exception was originating from. This makes debugging code really a hassle. I haven’t had this kind of problem in Java since nested exceptions.

Scripting The Night Away

One of the very nice features of Mac OS X ist the ability of almost every reasonable application to receive AppleEvents, which makes the whole OS-app-bundle highly scriptable. Normally, Apple recommends that the scripting is done using a malevolent, programmer-unfirndly language named “AppleScript”. But there are alternatives, e.g. using Ruby together with the rb-appscript library.

As a first try, I wrote a small hack solving the following problem:

In Aperture, I normally sort photos in folders named YYYY_MM_DD, so when I sort them by alphabet (or Aperture sorts them and I cannot change the sort order), the oldest ones show up first. Unfortunately, iPhoto imported photos from my camera in the German format DD.MM.YYYY, so the alphabetical sorting is useless.

The ruby script goes like this:

require "rubygems"
require "appscript"
include Appscript

app = app(‘Aperture’)
puts app.projects
app.get(app.projects).each { |project|
  name = app.get(project.name)
  if name =~ /^\d\d\.\d\d.\d\d\d\d$/
    day = name[0, 2]
    month = name[3, 2]
    year = name[6, 4]
    app.projects[name].name.set(year+"_"+month+"_"+day)
  end
}

Use quote_value in Rails 2

This is just a note to all who, like me, wonder why the heck ActiveRecord’s quote method in model classes doesn’t work anymore in Rails 2.x: quote seemingly has been replaced by quote_value, though this is not listed on the deprecation page. So if you get an error that says undefined method `quote’ for your model class, replace the calls to quote by quote_value.

ActiveRecord and Hibernate - Friends or Foes?

Currently, I am in the nice situation to decide for myself with which framework I will build a demonstration portal. So, as I want to profit from the fast-paced development processes (at least the Ruby aficionados say so) and the lightweightiness of Rails, I decided to go the Rail(s)Way.

Problem is, that I have to use a legacy database in PostgreSQL where I am not allowed to tinker with the structure, but I am forced to insert data into the tables. The database was created using Hibernate, which means an overall database sequence is used to generate the unique IDs. Unfortunately my new pal ActiveRecord does not know anything about global Postgres sequences, so I had to figure out a way to use the hibernate sequence in a hack to get my unique IDs.

What I did was to use the hook before_validation_on_create in the ActiveRecord table model to create an ID. This looks like this:

[ruby]
class Term < ActiveRecord::Base
before_validation_on_create :generate_id

private
# use the hibernate sequence to generate the next id
def generate_id
self.id = Term.connection,execute(”select nextval(’hibernate_sequence’)”).result[0][0]
end
end
[/ruby]

Scripting Happiness With Ruby’s ActiveRecord

I am currently enjoying the discovery of Ruby as a language for blazingly fast scripting database tasks. Like e.g. converting database records on the fly. The ActiveRecord module is a great help in that.

Quite Groovy

In the recent weeks, both of my co-bloggers told me independently of each other about Groovy, the new hipster language which brings the scripting goodness of dynamic languages like Ruby and Smalltalk to the JVM Sweet JVM, so I finally couldn’t resist but take a look at it. To be honest, I didn’t like its Java-like syntax from the beginning, with all the parentheses, lowerCamelCaseIdentifiers and such, but that was just because I prefer Ruby’s very lean syntax. Its concepts are very close to Ruby (modification of objects and classes at runtime, blocks/closures, etc.) and of course it integrates well with the Java platform and its rich libraries, since this is the purpose for which it was created, to add a scripting facility to the Java platform. Groovy scripts are compiled into bytecode before execution and thus run on a normal JVM.

A crucial part for dynamic languages today (at least in my eyes) is the creation of domain-specific language, which Groovy also supports. Gant, for example, is a Groovy DSL for Ant scripts. Another example (take from the Tutorial Domain-Specific Languages in Groovy, PDF) I find very practical is a DSL for creating query criteria for Hibernate in the Grails framework (formerly known as Groovy on Rails, so its purpose should be clear):

def c = Account.createCriteria()
def results = c {
  like("holderFirstName", "Fred%")
  and {
    between("balance", 500, 1000)
    eq("branch", "London")
  }
  maxResults(10)
  order("holderLastName", "desc")
}

A good thing, but looks too java-y for my taste, I miss the feeling I get when using a Ruby DSL, such as SQL-DSL, for example:

statement = Select[:column1, 'book', 10].from[:table1, :table2].where do
  equal :column1, 99
  not_equal :column1, 100
  less_than :column2, 'foo'
  less_than_or_equal :column3, :column4
  greater_than :column1, 0
  greater_than_or_equal :column2, 'bar'
  like :column1, 'any'
  is_not_null :column1
  is_in :column1, [1,2]
  is_not_in :column2, [3, 4]
  exists 0
  not_exists 0
end

But maybe that’s just personal preference.

From a few first glance I get the impression, that Groovy is quite successful as a scripting sidekick to Java and I’m curious to learn more about it.

Learning by Testing

A while ago, Mike Clark wrote two blog postings on how to learn Ruby by writing tests (#1, #2). He explains that he wrote a test for each bit he learned about the language, over the years collecting a set of more than 200 tests which act as his personal knowledge base on the Ruby language:

Through trial and error they taught me how Ruby and its rich set of libraries really work. Not surprisingly, typing in code and running it makes you remember. Indeed, writing learning tests is a fun way to poke and prod any new language or API. And with every test you write you’re investing in an executable knowledge base.

Unfortunately I never tried this myself, but I like the idea. According to him, the benefit is twofold: The tests assist in acquiring and checking knowledge (by what he calls “asking Ruby”) and act as a knowledge base that manifests itself in code (and some documentation, where needed, I’d like to add).

Yet I am a little bit skeptical about “asking Ruby”. In his second posting, he suggests to “make a guess” in a particular case where he doesn’t know the result of a method invocation (“Rick”.index(’t')). Maybe I’m a bit hypersensitive here, but I have some reservations when it gets to using tests to find out how things (could or should) work. I’d think it would it be better to just look it up in a reference and write the test afterwards. The main reason is that using one test case (or a few) will give you one (or few) results, from which you will have to draw conclusions and generalize—the semantics of the index method in this case. What if your conclusions are wrong for some exceptional cases? Is it possible/feasible/desirable to write tests for each and every combination of parameters for a method? Why not trying a “read first” approach?

Nevertheless, the basic idea of using test cases for playing around with a language and collecting them as a reference is a nice idea. I’ll almost certainly try this the next time want to learn something about Ruby or a different language.

IronRuby

Microsoft apparently hops on the dynamic languages train and releases IronRuby, a Ruby interpreter for the .NET platform which is also supported by Microsoft’s counterpart to Adobe Flash, the all new silvery Silverlight (which by the way also supports Python). I’m not exactly a fan of Microsoft, but I like the idea that web applets can now be written in Python and Ruby. How great would it be if these languages could once replace JavaScript on the client side as well. For now, I’ll stick with RJS templates for that purpose.

APIs and DSLs

Today I stumbled upon Josh Bloch’s talk How To Design A Good API and Why it Matters at Google Tech Talks. Its loaded with profound wisdom and advice from one of the masters of API design.

He explains that API design is very similar to language design, and I immediately thought that this particularly holds for APIs which are designed as domain-specific languages, which is one of Ruby’s strengths (read this article from Oreillynet.com to learn more about DSLs).

A few slides later he talks about characteristics of good APIs:

  • Easy to learn
  • Easy to use, even without documentation
  • Hard to misuse
  • Easy to read and maintain code that uses it
  • Sufficiently powerful to satisfy requirements
  • Easy to evolve
  • Appropriate to audience

To achieve all these properties for an API is certainly non-trivial, but at least some of them get easier if you design APIs as a domain-specific languages: As the term says, a DSL provides a language that is tailored for a particular domain, in addition DSLs are generally declarative and hide language aspects that are irrelevant. Such a language is obviously easier to learn, use and to read than a mere API, and is more appropriate to its audience. In the end, these are known strengths of declarative languages. Here’s an example taken from the Capistrano manual (Capistrano is a Ruby DSL for remote software deployment):
[ruby]
desc “Start the spinner daemon”
task :spinner, :roles => :app do
run “#{current_path}/script/spin”
end

desc “Used only for deploying when the spinner isn’t running”
task :cold_deploy do
transaction do
update_code
symlink
end

spinner
end
[/ruby]
Though this doesn’t hide imperative aspects completely, I think it’s a good example of how a DSL feels - just as if it wasn’t Ruby but a different language.

So, is it safe to conclude that DSLs are the better APIs?

iCal meets Google Earth

Some days ago I had this idea of a calendar browser showing my upcoming events in a 3D perspective, i.e. events of next week are close by while events some months away are far in the distance. The purpose is that I get an intuitive impression of things to come, their sequentiality and relation - something I miss in the typical grid-like calendar views offered by iCal and Outlook.  I talked about it to some of my colleagues and when I tried to explain the idea, I said something like “It should be like looking at Google Earth from a tilted angle, events placed on a sphere which I can roll back and forth“. It took me some moments, then it hit me: It’s easy to place markers on Google Earth by using KML files - and by using Google Earth as a platform, I get all the UI features I need for free.

Fast forward to one and a half days later: A very basic implementation of the “iCal meets Google Earth” mashup is ready, which I call einstein, well, because what it does is some kind of joining space and time. I used Ruby (of course), employing the vpim library for extracting iCal data and XML builder templates for creating the KML output. In the end it was almost too simple.

And this is what it looks like (by now):

einstein-screenshot

Next Page »