When working on a recent “top secret” project, I decided that my users needed vanity URLs. So, a user would have a “vanity name” of “foo”, and then requests to http://example.com/foo would need to redirect to that user’s profile (i.e. http://example.com/users/1). So I built a simple interface for doing that.
Then I thought, “hey, somebody could find this useful as a gem.” So I made one.
Vanities is a Rails 3 gem that gives you a quick and easy way to set up a model-agnostic system for vanity URLs throughout your Rails app.
A Quick Walkthrough
Vanities is meant to be really simple and easy to use. It’s not at all a groundbreaking, revolutionary concept or anything, merely a convenience for what could otherwise be a pain-in-the-ass kind of setup. Ergo, using it is a piece of cake.
Let’s start by creating a new Rails 3 application. This application is going to be a very (and by very I mean “extremely”) simple scaffold of users. We won’t be bothering with authentication or encrypted passwords, etc. in this example, as it’s just an example. But in reality, of course you’d have all that stuff.
Start by creating a new Rails application:
rails new mytestapp
The first thing we need to do is tell Bundler to use Vanities. Open your Gemfile and add this code:
Next, create a User scaffold. This is what will allow us to see Vanities working.
rails g scaffold user
Now, open the database migration for User and make it look like this:
class CreateUsers < ActiveRecord::Migration def self.up create_table :users do |t| t.string :name t.timestamps end end def self.down drop_table :users end end
Next, open app/views/users/show.html.erb and make it look like this:
<p id="notice"><%= notice %></p> <h1><%= @user.name %></h1> <%= link_to 'Edit', edit_user_path(@user) %> | <%= link_to 'Back', users_path %>
Now, type this in your terminal:
rails g vanities
This installs Vanities for you, including the route and controller responsible for making it all work. There’s only one more minor bit of code left to write – the has_vanity method. Open app/models/user.rb and make it look like this:
class User < ActiveRecord::Base has_vanity end
Finally, go back to your terminal and migrate your database:
Setting Up a Fake User
Now that we have Vanities set up, let’s create a fake user to illustrate. Issue the following commands in your terminal:
u = User.new(:name => “J. Austin Hughey”) # your name is fine here, too
u.vanity = Vanity.new(:name => “jah”) # you can use your initials here if you want
We just used the Rails console to create a user and a vanity for it, then saved it. This is necessary for our next step:
Now, go to http://localhost:3000/jah in your browser. You’ll be automatically redirected to the user’s view page. Welcome to Vanities!