A really simple Rails plugin to generate a unique code on a field for TinyURL style URLS
Ruby
Switch branches/tags
Nothing to show
Latest commit a4b789f Nov 9, 2009 @paulca paulca update the readme

README.textile

ShortcodeUrl

A simple Rails plugin to generate a unique code, for use in shorturl style situations.

You just need a field called ‘shortcode_url’ on your database table.

Nice and handy, nice and simple.

Example

Migration:


class AddShortcodeUrl< ActiveRecord::Migration
  def self.up
    add_column :posts, :shortcode_url, :string
    add_index :posts, :shortcode_url
  end

  def self.down
    remove_index :posts, :shortcode_url
    remove_column :posts, :shortcode_url
  end
end

Model:


class Post < ActiveRecord::Base
  shortcode_url
end

Usage:


@post = Post.new(:title => 'Bang!')
@post.save
@post.shortcode_url
# => 'MMhi'
Post.find_by_shortcode('MMhi)
# => <Post: @title => 'Bang!'>

Want a different column name? Add it as an argument


class Post < ActiveRecord::Base
  shortcode_url :secret_url
end

You can add as many of these as you like to get more than one shortcode per model:


class Post < ActiveRecord::Base
  shortcode_url :secret_url, :another_secret_url
end

If you want to specify the length of the shortcode, you can add a length attribute:


class Post < ActiveRecord::Base
  shortcode_url :length => 10
end

About me

I’m Paul Campbell. I’m an avid Ruby on Rails web developer. Follow my ramblings at http://www.pabcas.com

Follow me on Twitter http://twitter.com/paulca

Copyright © 2009 Paul Campbell, released under the MIT license