Boost Your Ruby Efficiency with Textmate

May 4th, 2009 by John Paul Narowski

Here at MetaSpring, we’re avid fans of the TextMate text editor because it makes developing web apps a breeze through the use of its hotkeys, snippets, and bundles.

TextMate comes with a plethora of basic language bundles – all of which come with their own set of custom hotkeys and snippets designed specifically for that language. These hotkeys and snippets can be customized for your preferences or you can even make your own.

At MetaSpring, we work predominately with Ruby and would like to share a few of the TextMate helpers that have made us all much more efficient developers. The following hotkeys and snippets can be found in the Ruby bundle, unless otherwise noted.

Helpful Hotkey Commands

The following commands can be found and managed by going to Bundles >> Bundle Editor >> Edit Commands.

Execute Line / Selection as Ruby

Control + Shift + E will execute a line or block of highlighted ruby code. The response will be outputted right after the executed code. This is extremely useful for testing Ruby syntax without having to switch to the IRB console.

Validate Ruby Syntax

Control + Shift + V will validate the syntax of your Ruby file. Try using this before running unit tests or reloading the server, it can save you tons of time spent repairing small syntax errors.

Run a file using Ruby

Command (⌘) + R will execute the file you are currently working on. One of our favorite features of this command is that it will also run RSpec tests if the file you have open is a spec file.

Convenient Snippets

The following snippets can be found or added to your TextMate environment by going to Bundles >> Bundle Editor >> Edit Snippets.

Create Hash Pairs and Hash Rockets

Hitting tab after entering a colon will produce a hash pair like :key => "value"
Control + L will produce a hash rocket with proper spacing =>

Params Shortcut

If you use Rails or Merb, you’ll most likely refer to a params[:x] variable frequently throughout the development cycle.
Control + P will output params[:id] where “id” is selected for editing.
Note: This snippet is included in both the Rails and Merb bundles.

Insert Comment Banners

Control + Shift + B sets up a comment block and allows you to enter the comment you want; a second tab gets you coding again.
Note: This snippet is included in the Source bundle.

Easy HTML Anchor Tags

Here’s an HTML snippet we made to make creating anchor tags a cinch.
Hitting Tab after entering an a outputs <a href=""></a>. You can then enter the link URL and hit tab to enter the link text.

To set this up in your own TextMate environment, create a new snippet with the following settings:

Anchor Snippet

Other Useful TextMate Bundles

With bundles for almost every programming and scripting language, the above examples are only a small sampling of the magic that TextMate is capable of. For more Ruby-relevant functionality, you might check out some of the following add-on bundles:

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Using Rails Migrations as part of a Simple Installation Script

February 23rd, 2008 by Carson Keith

Rails Migrations provide an easy way to make versioned revisions to your database structure over a period of time. When used properly they can make it easy to make modifications to your existing database programmatically as you need to make changes. This is extremely helpful for large up-and-running projects, but what about projects that are still in development? I don't know about you but for me, after working on large project for awhile there can be a ridiculous number migrations sitting around. It's also quite possible that a good portion of your earlier migrations have been nullified by other migrations later on. When you start throwing data into your migrations this can quickly become a tangled patchwork web of evil.

While migrations are extremely helpful for making modifications on production systems, we have found that having a pile of migration revisions really doesn't serve much purpose during the development cycle. This is especially true if you are not needing to work with live data and you have access to a good code repository like SVN. So during the development cycle for most of our Rails related projects we maintain one large initialization migration, an installation shell script, and a refresh shell script. The large migration handles the standard migration goodness, any type of data import, and other dynamic data installation initialization procedures. The installation script is run once to deploy the application on a new system; it typically sets up the database, runs the initialization migration, and handles whatever other settings you need for deployment. The refresh script simply refreshes the database and reruns the initialization migration; this is used when the migration is updated.

Below is a very simple example of how we put this idea to use:


Database Initialization Migration - 001_initialize_database.rb

require 'active_record/fixtures'
 
class InitializaDatabase < ActiveRecord::Migration
  def self.up
 
    # Initialize fixture array
    # This array is used to load a list of fixtures that will be loaded into the database at the end of the installation process
    fixture_array = []
 
    # It's important to use the :force option if you are not going to drop tables in your down method
    # this forces tables to be overwritten if they are already present
    create_table :customer, :force => true do |t|
      t.column :name, :string
    end
 
    # Add to fixture array
    fixture_array << :client
 
    # CREATE REMAINING TABLES
 
    # Load fixture data
    Fixtures.create_fixtures('db/fixtures', fixture_array)
  end
 
  def self.down
  end
end


Installation SQL Script - install.sql

CREATE DATABASE database_name_dev;
CREATE DATABASE database_name_pro;
CREATE DATABASE database_name_test;
GRANT ALL privileges ON database_name_dev.* TO 'user'@'localhost' IDENTIFIED BY 'password';
GRANT ALL privileges ON database_name_pro.* TO 'user'@'localhost';
GRANT ALL privileges ON database_name_test.* TO 'user'@'localhost';


Installation Shell Script - install.sh

#!/bin/bash
 
mysql -u root --password=password -e "source install.sql"
rake db:migrate


Refresh Shell Script - refresh.sh

#!/bin/bash
 
rake db:migrate VERSION=0
rake db:migrate

Then to install on a system we simply run install.sh from the command line.

> ./install.sh

If a change is made to the schema we run refresh.sh from the command line.

> ./refresh.sh

Since refreshing the database wipes the database clean and reloads each time, its really only useful until you have reached a final stage of deployment. Hopefully by that time though you will have a relatively stable db structure and won't need to be adding a butt-load of migrations.

It's really a relatively simple concept, but I can't tell you how much time we have saved in deployment using this methodology. We'd love to hear your ideas and deployment strategies.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Foreign Key to Foreign Key Relationships and Single Table Inheritance in Ruby on Rails

February 20th, 2008 by Carson Keith

ActiveRecord is great and efficient for simple normalized databases, but once you start tread off the beaten path ActiveRecord starts to lose a lot of its mojo. A few months ago I had a rather abstract database that utilized a number of models based on Single Table Inheritance (STI). Prior to refactoring our our database diagram looked something like an upside down untranslated Tokyo subway map. Fortunately single table inheritance saved our butt big time and we were able to knock off a number of confusing entities from the database and refactor in some common functionality. There was but one problem though. Before our moving to single table inheritance we had a few classes that looked something like this:

class Organization &lt; ActiveRecord::Base
end
 
class Client &lt; ActiveRecord::Base
  belongs_to :organization
end
 
class StaffMember &lt; ActiveRecord::Base
  belongs_to :organization
  has_many :clients, :through =&gt; :organization
end

After moving to single table inheritance it was something like this:

class Organization &lt; ActiveRecord::Base
end
 
class Client &lt; Organization
  belongs_to :organization, :foreign_key =&gt; 'parent_id'
end
 
class StaffMember &lt; ActiveRecord::Base
  belongs_to :organization
  has_many :clients, :through =&gt; :organization
end

It looked fine. I had only changed one thing in the client model, but now the has_many association in the StaffMember model just doesn't work anymore. I kept getting an error akin to:

ActiveRecord::StatementInvalid: Mysql::Error: #42000Not unique table/alias: 'organization': SELECT organization.* FROM organization organization.parent_id = organization.id WHERE ((organization.organization_id = 1)) AND ( (`organization`.`type` = 'Client' ) )

Well that just plain sucked... all of that refactoring seemed to have gone to waste. I scoured the net looking for a solution to my conundrum and I couldn’t find a single reasonable answer to it. I could have used the "finder_sql" option but then it only returns read only pseudo models. There just had to be a better way. I begrudgingly started to dig through ActiveRecord hoping to find a quick fix. Alas, I came back empty handed. I had almost lost hope when I realized I could just like the two foreign keys together between the Client and StaffMember model to get the same result as using the Rails has_many :through option. So I dug around a little bit more in ActiveRecord and added an “alternate_key” option to the HasManyAssociation class to define a different foreign_key instead of always needing to link to a primary_key. So now I could link directly to the Client model from the StaffMember model without needing to use the :through option. An example can be seen below:

class Organization &lt; ActiveRecord::Base
end
 
class Client &lt; Organization
  belongs_to :organization
end
 
class StaffMember &lt; ActiveRecord::Base
  belongs_to :organization
  has_many :clients, :alternate_key =&gt; 'organization_id', :foreign_key =&gt; 'organization_id'
end

Now @staff_member.clients should return a list of clients that are part of that StaffMember’s organization.

Download it

I have included the source below. Simply unzip it and drop it into your project’s lib directory and you should be all set. Download

Questions, Comments, Contiributions? Contact Me.

It’s really pretty simple at the moment and it only supports standard has_many relationships. If anyone has any questions or is interested in contributing ideas or code, please feel free to contact me at: A special thanks to Philip Koebbe for pointing out some flaws in my original post.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]