The addition of RESTful routing and the #to_param method in Rails has undoubtedly improved both the ease and usefulness of URL generation in Rails apps. However, there has come to be a rather insidious tendency to have an auto-generated id as the true reference for a given item. This may make sense for some or even many apps, but by and large records should be referred to by their content, not their ids, in URLs if at all possible. With this goal in mind, I have released from_param, a simple addition to ActiveRecord that makes it dead simple to use better URL finders.

Example

First of all, from_param is meant to simply be the complement of to_param, that is, you should be able to pass Model.from_param(some_parameter) the same way you would pass Model.from_xml(some_xml). Let’s examine how this works in practice:

class User < ActiveRecord::Base
  def to_param
    "#{id}-#{login.downcase}" 
  end
end

class UsersController < ApplicationController
  # GET /users/1-mbleigh
  def show
    @user = User.from_param(params[:id]) # => <User id=1 login="mbleigh">
  end
end

Simple enough, and it should look very familiar except that instead of a User.find or User.find_by_id, we have User.from_param. In fact, that’s exactly what this code does: from_param by default will call find_by_id since that is how the default to_param is configured.

Now let’s take something a little more complicated: a blog post title. I definitely don’t want an id in the URL if it’s a permalink, so how can I make an arbitrary parameter found as easily as the id? Simple, just add a param column to your table! Take a look:

class Post < ActiveRecord::Base
  def to_param
    "#{created_at.strftime("%Y-%m-%d")}-#{title.gsub(" ","-").downcase.gsub(/[^a-z0-9-]/,"")}" 
  end
end

class PostsController < ApplicationController
  # GET /posts/2008-04-26-from-param-plugin-released
  @post = Post.from_param(params[:id]) # => <Post title="From Param: Plugin Released" created_at="2008-04-26">
end

From Param will auto-magically save the to_param of your model to the specified parameter column (defaults to “param” but you can set it by calling set_param_column) and then automatically know to find by that column if it exists when from_param is called. This way, all you have to do is define a to_param that will be unique to your record and everything else is handled for you!

This plugin is really quite simple, but it establishes a convention that I feel has been missing from Rails for some time: a standard method to call to retrieve a record based on its URL parameter.

Installation

To install the plugin on Edge Rails or Rails 2.1 and greater:

script/plugin install git://github.com/mbleigh/from_param.git

On earlier versions of Rails:

git clone git://github.com/mbleigh/from_param.git vendor/plugins/from_param

Resources

If you have any suggestions for expanding the usefulness of the plugin or run into any problems, please report them on the From Param Lighthouse Project.

The issue of pre-loading needed data for a Rails application has always been somewhat confusing and difficult. A great post on Rail Spikes discusses the issue in-depth and offers a number of different solutions, but ultimately they all seem just a little short of the desired simplicity. By combining a few of the ideas and adding a few of my own, I have created a seeding system that I feel is very straightforward and easy to use.

Borrowing the basic premise of the db-populate plugin, Seed Fu is based around loading ruby scripts located in db/fixtures via a Rake task. What db-populate doesn’t offer is a clear syntax for describing the records to be seeded. That’s where Seed Fu comes in.

Usage

First, just create a new ruby script in db/fixtures (and create the directory itself, obviously). Any script that you drop in this folder will be automatically run when you execute your seeding rake task. Additionally, you can load environment-specific data by adding scripts in a folder of the same name (i.e. db/fixtures/development. In these scripts you can execute arbitrary Ruby code with the full Rails environment loaded; however, you should remember that this code will be executed every time the rake task is called and should not cause duplication or destroy anything that can’t be retrieved. The syntax for Seed Fu works as follows (with a User model as an example):

# db/fixtures/users.rb
# put as many seeds as you like in

User.seed(:login, :email) do |s|
  s.login = "admin" 
  s.email = "admin@adminnerson.com" 
  s.first_name = "Bob" 
  s.last_name = "Bobson" 
end

User.seed(:login, :email) do |s|
  s.login = "michael" 
  s.email = "michael@abc.com" 
  s.first_name = "Michael" 
  s.last_name = "Bleigh" 
end

The seed method is available on any ActiveRecord. It takes as parameters the ‘constraints’ for that seeding; in other words, the fixed attributes that will not change in the record’s life. The constraints are used to find the record and update instead of creating it with the attributes provided if it already exists. This way your seeds can change without mucking with other live data on your server.

Once you have set up your fixtures, it’s simple to run them:

rake db:seed

Or if you want to run them for a targeted environment:

rake db:seed RAILS_ENV=production

Installation

In edge Rails or Rails 2.1 and beyond:

script/plugin install git://github.com/mbleigh/seed-fu.git

In previous versions of Rails:

git clone git://github.com/mbleigh/seed-fu.git vendor/plugins/seed-fu

I have some ideas for the expansion of this plugin (loading from CSV for larger datasets, etc.), so stay tuned! If you have ideas for additional features or encounter any problems, I have set up a Lighthouse project for your enjoyment.

There are a number of times when I need something like an OpenStruct with a little more power. Often times this is for API-esque calls that don’t merit a full on ActiveResource. I wrote a small class for use with my ruby-github library and wanted to make it a separate gem because I think it’s pretty useful to have around.

Usage

Basically a Mash is a Hash that acts a little more like a full-fledged object when it comes to the keyed values. Using Ruby’s method punctuation idioms, you can easily create pseudo-objects that store information in a clean, easy way. At a basic level this just means writing and reading arbitrary attributes, like so:

author = Mash.new
author.name # => nil
author.name = "Michael Bleigh" 
author.name # => "Michael Bleigh" 
author.email = "michael@intridea.com" 
author.inspect # => <Mock name="Michael Bleigh" email="michael@intridea.com">

So far that’s pretty much how an OpenStruct behaves. And, like an OpenStruct, you can pass in a hash and it will convert it. Unlike an OpenStruct, however, Mash will recursively descend, converting Hashes into Mashes so you can assign multiple levels from a single source hash. Take this as an example:

hash = { :author => {:name => "Michael Bleigh", :email => "michael@intridea.com"},
       :gems => [{:name => "ruby-github", :id => 1}, {:name => "mash", :id => 2}]}

mash = Mash.new(hash)
mash.author.name # => "Michael Bleigh" 
mash.gems.first.name # => "ruby-github"

This can be really useful if you have just parsed out XML or JSON into a hash and just want to dump it into a richer format. It’s just that easy! You can use the ? operator at the end to check for whether or not an attribute has already been assigned:

mash = Mash.new
mash.name? # => false
mash.name = "Michael Bleigh" 
mash.name? # => true

A final, and a little more difficult to understand, method modifier is a bang (!) at the end of the method. This essentially forces the Mash to initialize that value as a Mash if it isn’t already initialized (it will return the existing value if one does exist). Using this method, you can set ‘deep’ values without the hassle of going through many lines of code. Example:

mash = Mash.new
mash.author!.name = "Michael Bleigh" 
mash.author.info!.url = "http://www.mbleigh.com/" 
mash.inspect # => <Mash author=<Mash name="Michael Bleigh" info=<Mash url="http://www.mbleigh.com/">>>
mash.author.info.url # => "http://www.mbleigh.com/"

One final useful way to use the Mash library is by extending it! Subclassing Mash can give you some nice easy ways to create simple record-like objects:

class Person < Mash
  def full_name
    "#{first_name}#{" " if first_name? && last_name?}#{last_name}" 
  end
end

bob = Person.new(:first_name => "Bob", :last_name => "Bobson")
bob.full_name # => "Michael Bleigh"

For advanced usage that I’m not quite ready to tackle in a blog post, you can override assignment methods (such as name= and this behavior will be picked up even when the Mash is being initialized by cloning a Hash.

Installation

It’s available as a gem on Rubyforge, so your easiest method will be:

sudo gem install mash

If you prefer to clone the GitHub source directly:

git clone git://github.com/mbleigh/mash.git

This is all very simple but also very powerful. I have a number of projects that will be getting some Mashes now that I’ve written the library, and maybe you’ll find a use for it as well.

Though I feel bad for jumping on the bandwagon, the Google App Engine is worth talking about because it represents what could be a major critical point in the development of web applications.

To this point the production of web applications has largely been the business of startups small and large. While the development of the applications involved can sometimes be a one-person operation, the infrastructure to run a production-ready scalable app has largely been beyond the reach of individuals and hobbyists. Google’s move, while still in its early stages, could be a watershed moment in app development.

De-Brandification

One thing that the App Engine might do is begin to separate web applications from the branding/marketing needs they currently have, at least in the initial stages. The app gallery access to a list of applications, all of which are easily accessible with your Google account, provides a brand-new experience for users. Rather than hearing about a new app that happens to do something that a user wants, instead they can now actively browse through a listing of applications, all rated and all easily accessible with a single sign-on. Do you care what company makes the widgets you stick on your Dashboard or your iGoogle page?

This isn’t necessarily bad news. Apps can still generate ad revenue and charge for services, but who makes the app becomes far less of a factor than how good it is at doing its thing.

Apps Get Smaller

With a central directory and a free base infrastructure, applications do not need to be all things to all people. They don’t even need to be most things to most people. The profit model for an application simply becomes a question of revenue recouping development time. While AWS provides a much less expensive server infrastructure than traditional mediums, the value of free cannot be underestimated, especially when it comes to the individual.

If a developer knows they can host an app that can scale to thousands of users with no cost, there is a stronger incentive than ever before for ‘the hobby project’, something that the developer thinks is cool but may or may not have real-world marketability. This is a dream come true in an increasingly agile industry: ‘throw it at the wall and see what sticks’ becomes not only viable but likely preferable when the barrier to entry is lowered by such a drastic degree.

Enter the Hobbyist

This low barrier to entry is going to foster a new generation of hobbyist apps. Many, perhaps most, will likely be worthless at least in some aspect. But a few will be brilliant gems, developed by a single person on a zero dollar budget. Hobbyists can create their projects on the side, release them in the wild, and see what gets a following, all at zero cost except the time spent developing the app.

This obviously isn’t applicable to all apps and situations, and venture-backed startups will still have just as much of a place, but the entry of hobbists into the web app mainstream could be a kickstart for competition and interoperability.

Nothing if Not Consistent

The final piece of the Google App Engine puzzle is that by providing a single platform – BigTable, Python, Google Account Access, and a standardized SDK, it will be much easier for App Engine projects to interact with each other semantically since they will all be built on essentially the same structure. As a Rubyist, I certainly look forward to more language support, but I think there is some power in the one-dimensional approach that, although it limits options, also provides a consistent target.

An analog to this is video game development. Up until the most recent generation, PC gaming was considered the platform for the truly ‘hardcore.’ But for developers, a consistent platform target that was deployed in millions and millions of homes won out against the configurability of the PC market. I think the same thing could be happening in the web app world: configurability is great, but if 90% of all apps can be hit by a single offering, it may be more worth it to have the consistency. This does not include language dependence, but if the App Engine SDK were available for all the big scripting languages, it would maintain that consistency while giving developers flexibility in implementation.

There are exciting times ahead, and the community will certainly be watching as more developments arise in the App Engine arena.

While the GitHub folks have produced their own github-gem that provides some useful command-line tools for GitHub users, the library they have written isn’t your traditional API wrapper since it’s focused around using GitHub rather than getting information from GitHub.

I’ve thrown together a small library called ruby-github that provides that kind of functionality. It’s extremely simple and works with all of the currently available API but that only comes down to three read-only calls at this point. Use like so:

user = GitHub::API.user('mbleigh')
user.name # => "Michael Bleigh" 
user.repositories # => array of repositories
user.repositories.last.name # => "ruby-github" 
user.repositories.last.url # => "http://github.com/mbleigh/ruby-github" 
user.repositories.last.commits # => array of commits (see below)

commits = GitHub::API.commits('mbleigh','ruby-github')
commits.first.message # => "Moved github.rb to ruby-github.rb..." 
commits.first.id # => "1d8c21062e11bb1ecd51ab840aa13d906993f3f7" 

commit = GitHub::API.commit('mbleigh','ruby-github','1d8c21062e11bb1ecd51ab840aa13d906993f3f7')
commit.message # => "Moved github.rb to ruby-github.rb..." 
commit.added.collect{|c| c.filename} # => ["init.rb", "lib/ruby-github.rb"]

Installation

The easiest way to install ruby-github is as a gem:

gem install ruby-github

You can also install it as a Rails plugin if that’s your thing:

git clone git://github.com/mbleigh/ruby-github.git  vendor/plugins/ruby-github

Update 4/12/2008: Version 0.0.2 of the gem has been released and I have revised this post to adhere to the new gem’s requirements.