Racksh: A Rails-Console-A-Like for Rack-Based Ruby Apps

Have you ever yearned for something like Rails’s script/console or Merb’s merb -i in your other Rack based apps? If so, then Marcin Kulik‘s racksh, inspired by Heroku’s console, might be for you.

Racksh is a console for Rack based ruby web applications. It allows you run a console in the context of an application environment for Rails, Merb, Sinatra, Camping, Ramaze (or even your own framework) provided there is a rackup file in the root directory.

When you run the racksh command, it loads the whole application environment just like a Rack web server, but instead of running the app it starts an irb session where you can invoke commands.

$ racksh
Rack::Shell v0.9.4 started in development environment.
> Article.all
=> # returns all articles...

As of version 0.9.4 (released this week), racksh uses Bryan Helmkamp’s rack-test to simulate HTTP requests to your Rack application via the $rack variable.

$ racksh
Rack::Shell v0.9.4 started in development environment.
> $rack.get "/"
=> # returns a Rack::MockResponse

Racksh also allows you to apply configuration through a .rackshrc file. This can be used to set headers which will be used for requests, or to make additional setup requests (e.g. to make sure a user is logged in).

Install as a gem from Gemcutter, or get the source from Github.

gem install racksh -s http://gemcutter.org

For more details, check out the project’s README, and these recent posts on Marcin’s blog.

Jekyll: A Ruby-Powered Static Site Generator

jekyllJekyll is a simple Ruby-powered static site generator, originally by Tom Preston-Werner (aka mojombo) of Github fame. It’s focused around blogging, but it can be configured to generate any kind of static site. (Note: Jekyll has been around for about a year – Tom originally blogged about it in November last year, so apologies if this is old news to some readers, but I’ve only recently discovered it!)

Because Jekyll outputs a static site structure, it means you can host your blog (or site) from anywhere that you can serve static HTML, simply by using your favourite web server (e.g. Apache). As Tom describes in his blog post, the idea came from wanting to be able to “Blog like a Hacker”. Jekyll lets you write from the comfort of your favourite text editor, and publish from the command line. Using familiar tools reduces the cognitive load involved with publishing a blog, and lets you focus on what you’re writing. It doesn’t hurt that even a pretty weak Web server could stand a pounding if it’s just serving static files!

By default, Jekyll uses its own (slightly modified) flavour of Liquid templates, with help from pygments for syntax highlighting, and you can use textile or markdown for the content. Each Jekyll blog article template needs a header containing some metadata about that article, such as what layout to use, the article’s title, and any custom information you want to provide (such as tags for that article).

Generating your site is easy: just running the jekyll command turns your directory of templates into a complete website, ready to serve. There’s a Jekyll server that you can use for testing (passing --auto as an argument means it will automatically regenerate the site when things are changed).

jekyll --server --auto

Github Pages provides a neat way to publish your Jekyll-generated site. Every Github page is actually run through Jekyll when you push content to your pages repo (this works because a normal static site is also a valid Jekyll site).

The easiest way to get started with Jekyll is by installing the gem (which is available on Gemcutter), and checking out the wiki on Github, where there’s some great documentation.

sudo gem install jekyll

As you might expect, Tom Preson-Werner’s personal blog runs on Jekyll. Its source is publicly available on Github.

Riot: for fast, expressive and focused unit tests

JustinRiot is a new Ruby test framework by Justin Knowlden that focuses on faster testing. Justin was frustrated with his slow running test suites, despite employing techniques such as using factories, mocks and avoiding database access. He realized that a slow-running suite makes one reluctant to run it or expand it – not good.

With Riot, each test consists of a block which forms a single assertion on the topic of the test, keeping the tests focused. Tests run in a specific context, and the setup code is only run once per context, further contributing to the speed of your test suite, and unlike some Ruby test frameworks, such as Shoulda, that rely on or are based on Test::Unit, Riot has taken a new approach for speed purposes. In Justin’s own comparisons, Riot comes out about twice as fast as Test::Unit.

Here’s an example Riot test (from the README):

context "a new user" do
  setup { User.new(:email => 'foo@bar.com') }
  asserts("email address") { topic.email }.equals('foo@bar.com')

Riot’s comprehensive README also includes lots of examples and details on how to modify your Rakefile to run your Riot test suite in different frameworks. The full documentation is available online here.

You can install Riot as a gem from Gemcutter:

sudo gem sources -a http://gemcutter.org
sudo gem install riot

Justin also has a spin-off project called Riot Rails, which includes some Rails-related macros for testing your Ruby On Rails code, and Alex Young has written a Javascript port of Riot which is worth checking out too. He also has his own look at Riot and demonstrates how Riot can reduce redundancy in tests.

CodebaseLogo-RI.png[ad] Codebase is a fast & reliable git, mercurial & subversion hosting service with complete project management built-in – ticketing, milestones, wikis & time tracking – all under one roof. Click here to try it – free.

Mustache: Logic-Free Views For Your Ruby Web Apps

mustacheMustache (or GitHub repo) is a new templating library from Chris Wanstrath (a.k.a. defunkt of GitHub fame) that provides a way to render views in your chosen Ruby web framework. Influenced by ctemplate, Mustache helps to keep your MVC layers separate by actively preventing the inclusion of application logic in your views.

With Mustache, the typical view layer is split up into two sub-layers: a Ruby Class-based “view” and an HTML “template”, so you can concentrate on crafting your HTML without polluting it with embedded Ruby logic. This separation also makes it easier to test your view-code.

Amusingly, the name of the project comes from the way that you insert references to the view class into the template. Tags are denoted by double curly braces, or “mustaches”. e.g. {{name}}.

In their simplest form, tags are just calls to methods on your Ruby view class. But they can also take more complex forms such as block definitions, calls to partials or helpers (from modules included into your view class).

There are more examples and documentation in the GitHub project, but here’s a canonical usage example from the README:

View Logic:

class Simple < Mustache
  def name

  def value

  def taxed_value
    value - (value * 0.4)

  def in_ca


Hello {{name}}
You have just won ${{value}}!
Well, ${{taxed_value}}, after taxes.

At the moment, only Sinatra support is provided “out of the box”, but it should be fairly easy to integrate with other Ruby frameworks.


Mustache is available from Gemcutter or Rip. Install in one of two ways:

$ gem install mustache
$ rip install git://github.com/defunkt/mustache.git

CodebaseLogo-RI.png[ad] Codebase is a fast & reliable git, mercurial & subversion hosting service with complete project management built-in – ticketing, milestones, wikis & time tracking – all under one roof. Click here to try it – free.

Watchr: A Flexible, Generic Alternative to AutoTes

watcherWatchr is a continuous-testing tool by Martin Aumont in the vein of Autotest (part of the ZenTest package).

At its heart, Watchr basically watches any (or all!) of your project’s files, then executes arbitrary Ruby code of your choice when things change.  Watchr configuration takes such a form:

watch('pattern') { |match_data_object| command_to_run }

For example, to produce Autotest-like functionality, you’d just specify Watchr to run the tests whenever a test or some library code changes, like this (taken from Martin’s blog post):

watch('test/test_.*\.rb') { |md| system "ruby #{md[0]}"}
watch('lib/(.*)\.rb')     { |md| system "ruby test/test_#{md[1]}.rb"}

…but Watchr can be used for much more than just testing. You could use it to automatically generate documentation, build your gem or any other tasks that you can script in Ruby.

To get started with Watchr, just install the gem (from Gemcutter), and run the watchr command from your project root, passing the location of the configuration script:

$ gem install watchr --source=http://gemcutter.org
$ cd to/your/project/root
$ watchr path/to/script

The source and some documentation (including example scripts) is available on Github, and you can read more on Martin’s blog too.

If an even more simplistic route appeals to you, Ruby Inside’s editor, Peter Cooper, has a basic Rake task that can run a script of your choice when files change within a project.

devver-icon.gifAlso.. Got a slow Test::Unit or RSpec suite? Run them up to three times faster on Devver’s cloud! Setup is simple and requires no code changes. Sign up now!

Coulda: A Cucumber-like DSL for BDD

cucumberEvan Light has recently pushed his Coulda project to Github – it’s a test framework based on Test::Unit, inspired by Cucumber, Shoulda and Thor.

Coulda works like Cucumber in that it’s a Domain Specific Language for capturing the behaviour expected by your code, as part of the Behavior Driven Develoment approach (BDD). Others have noted it’s a little like the RSpec story runner.

Where Coulda differs is that instead of using Gherkin to convert your statements about the behavior to code using regular expressions, it uses standard method calls. This is less of a cognitive leap for the developer… with Coulda, you can test like you code.

require 'rubygems'
require 'coulda'
include Coulda

Feature "feature name" do
  in_order_to "foo"
  as_a "bar"
  i_want_to "blech"

  def something

  def expectation

  Scenario "pending scenario"

  Scenario "another scenario" do
    Given "a pending prereq"
    When "something happens" do
    Then "expect something else" do

  Scenario "that is live" do
    Given "foo" do; end
    When "bar" do; end
    Then "blech" do; end

To be honest, I’m not a big user of Cucumber, so I’m not able to give much of an intelligent commentary here, so I suggest you read more about Coulda on Evan’s blog. You can get the code on Github.

devver-icon.gifAlso.. Got a slow Test::Unit or RSpec suite? Run them up to three times faster on Devver’s cloud! Setup is simple and requires no code changes. Sign up now!

Review of The Merb Way by Foy Savas

the merb wayI’ve been reading the Merb Way by Foy Savas (Addison Wesley).  I was a little sceptical about this book at first, because of the recent marriage of the Merb and Rails core teams and the announcement that the Merb codebase would be merged with Rails as part of the march towards Rails 3. As Yehuda Katz put it, “Merb 2 is Rails 3”.

So, is this book now redundant?  I don’t think so. As Obie Fernandez explains in the foreword, knowing about Merb is still valuable as it is a fairly widely used framework, and it will probably continue to be seen in the wild for a good while after Rails 3 is released.  Additionally, learning how Merb works and exploring the underpinning philosophies will aid your understanding of some of the changes happening in Rails.

The book itself is engaging and well written, and serves as a great reference guide for developing Merb applications.  It’s quite code-heavy, but this is by no means a criticism – Foy guides the reader through the Merb source, revealing how things are done in Merb, in order that the Ruby community can learn from it for developing our applications and future frameworks.

With under 300 pages of actual content, this is by no means a weighty tome, but it covers most things a Merb developer needs to know.  Foy starts with the fundamentals, explaining how Merb apps are structured and configured, as well as providing an introduction to some of the internals of Merb. The first part of the book is concerned with routing and MVC, which will be familiar to Rails developers.  It then moves onto more Merb-specific topics such as slices (self-contained mini-apps that can be packaged as gems) and parts (for reusable logic used in partials throughout your app). Sessions, authentication, and mailers are also covered, before the book concludes with a chapter on testing.

The Merb Way is available now from Amazon for $29.19 (or £23.19 from Amazon UK).

CouchRest: CouchDB, Close to the Metal

couchI have been contemplating the use of document-stores in my Ruby apps for a few months (you might remember my MongoMapper post from back in June), and I’ve been following developments in the No-SQL movement. George Palmer’s presentation at Rails Underground on his couch_foo gem inspired me to explore the possibilities further, and I’ve recently started work on incorporating CouchDB into some projects that I’m working on.

What is a “document store?”

Couch is one of several available document oriented databases (the other main contender being MongoDB, for which there’s a good comparison on the Mongo website). Document stores go some way to bridging the gap between traditional functionality-rich relational databases (like MySQL, Postgres) and fast, highly scalable key/value stores (such as Toyko Cabinet). I think I should make it clear at this point that I’m not a SQL-hater: I worked as a DBA for a while a few years ago, and if you have truly relational data with a fixed schema and complex transaction requirements then you can’t beat a good RDBMS.

With CouchDB and friends, data is held in documents. These documents don’t have a fixed schema – they can have any number of arbitrary properties. This makes document stores great for holding collections of similarly (but not identically) stuctured items. CouchDB stores the data as JSON hashes, and provides a REST interface for creating, updating and querying.

Using CouchDB in your Ruby App

I’ve already mentioned couch_foo as one option for interacting with a CouchDB from Ruby app but after a bit of investigation, I eventually decided against it. Although it provides a familiar ActiveRecord-style interface and seems well-written, I wanted something that was a bit closer to couch’s RESTful HTTP and JSON interface. Also, I wasn’t convinced that extending the ActiveRecord paradigm to a document-based database was a good fit. I also dabbled with Alex Lang’s couch_potato library, but finally decided on CouchRest.


CouchRest lightly wraps CouchDB’s HTTP API (via RestClient, Heroku‘s Ruby HTTP wrapper), and provides a simple, Object-Mapper agnostic framework on which to build your application. Things just work as you’d expect: the JSON that comes back from CouchDB queries are presented as objects based on Ruby Hashes.

Models, Properties and Views

With CouchRest, you can define models for documents that share similar structures, deriving from CouchRest::ExtendedDocument. Properties that are common to each Model can be declared with CouchRest’s property method. It also supports the automatic setting of created_at and updated_at properties, callbacks and validations.

In Couch, you query and filter your data via views. Views are declared as javascript map-reduce functions that iterate through all documents in the database, building an ordered index of key-value pairs. CouchRest lets you declare simple views in Ruby, so that you can look up documents by that property. If you need more control, there’s also the option of passing the raw javascript to the Ruby method.

class Article < CouchRest::ExtendedDocument

  include CouchRest::Validation

  property :date
  property :title
  property :slug

  view_by :slug

  validates_present :title


  save_callback :before, :generate_slug_from_title

  def generate_slug_from_title
    self.slug = title.downcase.gsub(/[^a-z0-9]/,'-').squeeze('-').gsub(/^\-|\-$/,'') if new?

Hopefully this has given you a taster of what CouchDB might be good for, and how CouchRest can help you with integrating it into your Ruby app. Obviously there’s much more too it than I’ve covered here, but this (draft) online O’Reilly book is a great place to start learning about CouchDB …and it’s co-written by J. Chris Anderson, author of the CouchRest Ruby library.

jslab.pngJumpstart Lab is running a JavaScript Master Class for Javascript & UI programmers with Thomas Fuchs (Scriptaculous, Prototype Core) and Amy Hoy (UI Expert) on 9/12 in Washington, DC. Save 10% with code “rubyinside”!

Gemcutter: A New Gem Hosting Repository Taking Aim At RubyForge and GitHub

ready set goGemcutter is a new gem hosting repository that aims to replace RubyForge as the canonical repository for gems. The project has been around for a couple of months, but Thoughtbot recently announced they’re helping out with a forthcoming redesign of the site

As part of the plan to get everyone using it as their main gem repository, Gemcutter has already imported all of the gems that were on RubyForge – meaning there are over 5000 gems on there already.

After installing Gemcutter (with gem install gemcutter), consumers of gems just need one command to set Gemcutter up as their primary source:

gem tumble

As a publisher, you can just use the git-esque “gem push” command to release a new version of your gem. 

gem push yourgem-0.0.1.gem

If you had a gem on Rubyforge and it has been migrated across, then there’s a simple procedure for claiming it.

Other than ease of publishing, other benefits of Gemcutter include the way it sidesteps the confusion surrounding Github’s naming policy for gems (i.e. prepending the Github username to the gem), and that it provides easy, obvious access to project-pages for the gems.

When I first came accross Thoughtbot’s post on the Giant Robots blog, I originally thought that Gemcutter belonged to them, and great as Thoughtbot are, I was still a little bit worried about a single company taking ownership of a large slice of Ruby-community real-estate. Nick Quaranto, the owner of the Gemcutter Github repo (and intern at Thoughtbot) has assured me, though, that it belongs to the community first and foremost.

Support from: New Bamboo – London’s leading Ruby consultancy is looking for an experienced developer to join their team. Click here to learn more about the position.

Monk: A Ruby Glue-Framework for Web Development

monkI recently came across the interesting-looking Monk framework. It allows you to specify a list of dependencies for technologies to use in your project (in the form of git repositories or gems), and it will take care of extracting them into your application’s vendor folder.

With the default skeleton (for which you’ll need a Redis key/value database installed), you’ll get a Sinatra application with Haml, Rack, Contest, Stories, Webrat and Ohm. However, you can create your own skeleton with its own dependencies if you like.

You can install Monk with:

gem install monk

… and then initialize a project with the default skeleton:

monk init myapp

This will give you a familiar structure with helpers, models, routes, views, lib and vendor folders.

For more details, check out the Monk website.

Support from: New Bamboo – London’s leading Ruby consultancy is looking for an experienced developer to join their team. Click here to learn more about the position.

Whois: A New Pure-Ruby Whois Gem

guess who?Simone Carletti of Altura Labs recently announced on his blog the release of a new pure-Ruby Whois library, inventively named “Whois“.

He needed a whois library for one of his projects, but found that the existing options didn’t satisfy his requirement of being able to query both IP addresses and top level domains.  Simone’s offering replaces the original whois gem by Cyril Mougel, with which it’s backward compatible.

Using the ‘all-in-one’ whois class-method will give you the default behaviour, with a timeout of 5 seconds. If you want more control you can initialize a new instance of the client:

# => whois response for rubyinside.com

client = Whois::Client.new
client.timeout = 3
# => whois response for

For more details, check out Simone’s blog post, the docs, and the Github repository.

Bowline: An MVC Framework for GUI Apps in Ruby

bowlineBowline is a new MVC GUI framework for developing cross-platform desktop applications using Ruby, HTML, CSS and Javascript. The author, Alex MacCaw, aims to make building a desktop app as simple as creating a Rails site.

Unlike pure Ruby desktop libraries like Shoes, Bowline builds on Appcelerator Titanium, an SDK for building desktop apps that basically gives you a Webkit window and a set of APIs for interacting with various operating systems. This lets you develop for the desktop using familiar web technologies, including CSS3 and HTML5 (think Adobe Air!).

To allow your Ruby code to interact with your HTML, Bowline introduces the concept of “binders” which can update your views as the underlying data changes (a bit like controllers in Rails). Bowline also includes other ideas analogous to parts of the Rails framework, such as generators, helpers and models.

In this blog post Alex MacCaw shows off a simple Twitter client he built using Bowline – you can download it and continue to play on your own if you like. Nice work!

Support from: New Bamboo – London’s leading Ruby consultancy is looking for an experienced developer to join their team. Click here to learn more about the position.

Chef: Quick and Tasty Ruby Powered Server Configuration

chefChef isn’t exactly new, but I’ve been looking into it recently after briefly talking to Lindsay Holmwood at Rails Underground.

Basically, Chef is a Ruby-based configuration management engine. You set up recipes for how you want your system configured, and then Chef will cook it up for you.  So, you can write lovely Ruby code to manage your servers, rather than running commands directly on your server.

With Chef, one of your systems is the server and all others are clients that communicate with the Chef “server” via REST over HTTPS. The server is a Merb application that stores cookbooks for your nodes using CouchDB.

The work is done by the clients, running the recipes for one or many nodes thus configuring that particular machine. The Chef server is only there to provide information to the clients.  Once configured, you can access your Chef server and its cookbooks via a Web interface.  You can create your own cookbooks from scratch but it’s worth checking to see if one already exists in the Chef repository or one of its forks.

Once you’ve got your recipes sorted out, Chef allows you to programatically set up and commission production-ready server instances in next to no time.

Ezra’s Cooking with Chef 101 blog post is a great place to get started, and there’s a wealth of information in the Opscode Chef wiki. The Superfeedr blog post, Scale With Chef, is also worth a read.

jslab.pngAlso.. Jumpstart Lab is running Rails Jumpstart – an intro to Rails – on August 15&16 then JavaScript Jumpstart for intermediate Javascript & UI programmers on 9/12. All courses are in Washington, DC. Save 10% with code “rubyinside”!

The Rails Underground 2009 Keynotes: Fred George and Yehuda Katz

rails undergroundI attended the Rails Underground conference in London at the weekend (July 24-25, 2009). As always seems to be the case at these events, I got the most value out of the more theoretical and opinion-based talks rather than ‘how-to’ style presentations. Having said that, Pat Allan and George Palmer gave great talks on their respective thinking_sphinx and couch_foo plugins.

I’m going to concentrate on the keynotes from the two days, which give quite differing perspectives.

Fred George – Rails is a hammer. Not everything is a nail.

fred georgeIn the keynote (video link) for the first day, former Thoughtworker, Fred George warned us against using Rails for the wrong kinds of projects.  He started off by discussing how frameworks like Rails let you get started quickly but become harder to manage as the complexity of your problem increases.

The rest of the talk consisted of Fred explaining the architecture of a project for which he decided to roll his own framework with only the parts he needed.  Fred explained that he wasn’t a fan of using SQL-based traditional relational databases, as it can force your object model into an unnatural form that might not suit your problem domain. Fred’s project consisted of a HAML/SASS front-end with Sinatra and pure-Ruby models persisting data to YAML files.  The problem I have with this kind of approach is that by relying on a disparate set of technologies you run the risk of one or more component becoming obsolete over time.

As a couple of people in the audience mentioned afterwards, Fred didn’t really give an exhaustive comparison of Rails versus the alternatives, as he was basically just describing one particular application that he’d written but the basic message that I got from the talk was that if your domain model fits well with a relational database structure, then traditional MVC with Rails is a good fit (e.g. administering users).  However, a service that just exposes the DB structure and its contents isn’t adding much value (i.e. REST/CRUD on a set of tables).  To add value you need to design the models intelligently.

Yehuda Katz – the future is granular

yehudaYehuda Katz gave the keynote (video link) for day two, about how Rails is evolving.  Yehuda explained how the Merb and Rails core teams have come together to try to work on Rails 3.0 – a fusion of the best parts of each framework, but with re-imagined internals.  Rails 3.0, isn’t going to remove any of what makes Rails great, but it will hopefully be better for ‘power users’.  i.e. those developers who care about how the internals work, and take advantage of the concepts therein.

A large portion of the keynote involved an explanation of why interfaces are a good abstraction.  (Not the Java kind of interface, but the hypothetical kind – i.e. contracts between components). Interfaces give you a calling-convention, allowing you to change internal implementations without affecting the calling code.  Classes and modules take this to the next level: mixing in modules is more powerful than inheritance as it allows your classes to learn new things. As Yehuda put it, “Your parents didn’t define all that you can do when you were born. You can learn new things.”  With Ruby modules you can swap out small sections of implementations as and when you need them at runtime.

This concept is used to allow the different components of Rails 3.0 to be separated up.  For example, you will no longer be forced to use ActionView – you’ll just need something that is “ActionView compliant”.  The same applies to ActiveRecord – your models will just need to comply with the ActionModel contract.

Despite what you might think, the contracts for ActionView and ActionModel compliance are actually really simple, and just need a few methods.  If you just want the default behaviour, all you’ll need to do is just include an existing module.  By implementing these interfaces you will end up with something that ‘just works’ with ActionPack, providing you with all the usual form and error helpers.  Furthermore, ActionController::Base will essentially just be ActionController::Metal with a bunch of extra modules included… but you can still use a stripped down version of metal if you don’t need all that extra functionality.

So, all of this will result in a much more granular Rails which will allow you to opt in or out of each part if that’s what you want.  By just pulling in the parts of Rails you need, you can reduce memory usage and complexity in your apps.  This goes some way to answering Fred George’s criticisms of Rails, regarding not being able to just select the parts you need for the job. And maybe it will unite the Ruby community by allowing people to focus on just one de-facto implementation of each component.

Links to slides and videos for each presentation made at the conference can be found on the schedule page of the Rails Underground site.

jslab.pngAlso.. Jumpstart Lab is offering workshops teaching Ruby for beginning female programmers (Ruby Jumpstart) on August 1st and 2nd, then beginning Rails (Rails Jumpstart) for everyone on August 15 & 16. Save 10% with code “rubyinside”!

Backgrounded: A Simple Wrapper for Ruby Background Tasks

backgroundedLike Ryan Sonnek, I’ve dabbled with a few different ways to run background processes in my Ruby apps, even resorting to knocking together my own (far from perfect) solution. As Ryan says on his blog, many popular libraries have complicated interfaces and don’t “feel right”.

I tend to disagree, however, with his statement that every ruby background job solution sucks, and I’m sure he doesn’t really mean it. Although his offering, Backgrounded, is refreshingly simple and concise, it’s effectively just a wrapper for other solutions.

With Backgrounded, if you want a certain method to always run in the background, you can specify it like this:

class User
  backgrounded :do_stuff

  def do_stuff
    # do all your work here

…and then just call that method in the normal way. The actual background work can be taken care of by a handler of your choice, but delayed_job comes bundled.

Ryan’s meta-programming approach for declaring background tasks doubles-up as documentation, and puts the focus on the individual methods rather than requiring you to create separate classes for your jobs.

Get Backgrounded as a gem or download the source from Github.

Make any Ruby object Rack-friendly with Rackable

rackFrançois Vaux has recently published a Ruby module called Rackable which allows you to make any Ruby object Rack-friendly, providing it with a REST-like interface.

What does this mean? Well, a Rack application is essentially a Ruby object that responds to call(). Rackable just gives your object a call method which uses the Rack environment to dispatch to a method.

So, you just need to include Rackable in your class and implement methods for the the appropriate REST verbs. This means you can create a hello_world.ru file like this:

require 'rackable'

class HelloWorld
  include Rackable

  def get()
    "Hello, world!"


run HelloWorld.new

… start it with rackup, and then use something like curl (or even your browser) to call the methods.

Thanks to Alex Young for putting me on to this.

devver-icon.gifAlso.. Got a slow Test::Unit or RSpec suite? Run them up to three times faster on Devver’s cloud! Setup is simple and requires no code changes. Request a beta invite today!

Patron: A Simpler Ruby HTTP Client for Ruby

Phillip TolandUntil recently, I had been using the Curb library for making HTTP requests with Ruby, and I must say I was fairly happy with it. Phillip Toland, on the other hand, wasn’t satisfied with Curb’s API and the fact that it is tricky to modify (being implemented mainly in C). So, he came up with an alternative called Patron, written as much as possible in Ruby.

Patron is based on libcurl, just like Curb, but it aims to provide a simpler interface whilst still taking advantage of libcurl’s strengths. To use Patron you can instantiate a Session object with your desired options:

sess = Patron::Session.new
sess.base_url = "http://search.twitter.com/"

…and then call methods against that session to perform your GET, HEAD, PUT, POST or DELETE operations. For example:

response = sess.get "search.json?q=ruby"

I really like the way that Patron lets you can send custom headers with your request, as I found this a bit fiddly in Curb.

sess.post("/foo/stuff", "some data", {"Content-Type" => "text/plain"})

Phillip provides more background about his design choices on his blog. You can find Patron on Github or install it as a gem.

Siren: a JSONQuery interpreter for Ruby

sirenSiren is a JSON and JSONQuery interpreter for Ruby by James Coglan. Before I dive into talking about Siren, a little bit of background:

JSON is a lightweight, human-friendly data interchange format, for which there is already good Ruby support in the form of the json gem. JSONQuery was originally added as part of the dojo javascript toolkit and provides querying tools for JSON such as filtering and sorting etc. (check out this article on SitePen for more details). You can also find a stand-alone port of JSONQuery on Github.

Anyway, using Siren lets run queries against any type of Ruby object. In addition to the standard JSONQuery features, Siren allows JSON objects to be assigned IDs, enabling cross referencing and cyclic data structures. It also allows you to tell the parser to cast objects to an instance of a particular type, populating instance variables with the data (rather than just using vanilla hashes or arrays like most JSON tools).

Siren is available on James’s Github account. Check out the README for more details on the supported features.

jslab.pngAlso.. Jumpstart Lab in Washington, DC is offering workshops teaching Ruby for beginning female programmers (Ruby Jumpstart) on August 1st and 2nd, then beginning Rails (Rails Jumpstart) for everyone on August 15 & 16. Save 10% with code “rubyinside”!

Alias: Enhance Your Ruby Console/irb Experience

aliasA couple of weeks ago we featured Gabriel Horner‘s Hirb framework for formatting irb output. I’ve recently been playing with another of his projects, Alias, which further enhances the Ruby Console experience (but it conceivably could be used in your Ruby programs too).

It’s already possible to set up aliases in your .irbrc file, but this can get confusing and it’s easy to run into conflicts. Alias takes a more structured, hash-based approach which (by default) lets you set up aliases for constants, instance methods or class methods. For example:

create_aliases :instance_method, "ActiveRecord::Base"=>{"update_attribute"=>'ua'}

You can store and retrieve your aliases in an easy-to-read YAML configuration file and it’s simple to have script/console (or irb) load them automatically from that file on start-up, by adding a small amount of code to your environment.rb (or .irbrc) file.

Extending Alias is fairly straightforward. Just subclass Alias::Creator and implement a few methods for mapping the aliases, checking their validity and generating the Ruby code to be evaluated.

For more details, check out the documentation and Gabriel’s recent blog post. You can install the gem from Github with:

sudo gem install cldwalker-alias -s http://gems.github.com

jslab.pngAlso.. Jumpstart Lab is offering workshops teaching Ruby for beginning female programmers (Ruby Jumpstart) on August 1st and 2nd, then beginning Rails (Rails Jumpstart) for everyone on August 15 & 16. Save 10% with code “rubyinside”!

Gibbler: Git-like Hashes and History for Ruby Objects

gibblerInspired by Git (the version control system), Delano Mandelbaum has come up with a library called Gibbler, which produces hashes and history for Ruby objects.

Calling the gibbler method on an object will produce a 40 byte git-like SHA1 hash (or you can use gibbler.short to get just the first 8 bytes).

my_object.gibbler.short # => 4c558a56

Gibbler can also track changes to an object. Every time you call gibbler_commit, it will create a clone of the current object and store it in an instance variable. And just like with git, you can view or revert to any version in the history. By default Gibbler supports history for Hashes, Arrays and Strings.

Get Gibbler and read the documentation on Github. Delano makes the disclaimer that his code is still very new and not particularly efficient (due to keeping everything in memory), but he invites others to play with it and submit patches.

Support from: Brightbox; – Europe’s leading provider of Ruby on Rails hosting. Now with Phusion Passenger support, each Brightbox server comes with access to a managed MySQL cluster and redundant SAN storage. Brightbox also provides managed services for large scale applications and dedicated clusters.