deliciously simple web design & creatively technical writing
This is my entry for the Railcasts Contest by Ryan Bates. If you’re not checking out this site and you’re at all interested in Rails, you’re missing out.
Lately I’ve been very interested in harnessing the power of regular expressions in my own Ruby On Rails projects, so here I present 5 relatively simple ways you can use them yourself.
What are regular expressions used for?
Regular Expressions provide a way to use horribly cryptic and ridiculously non-human syntax to match patterns in text.
If you’ve ever seen a code sample that contained anything incomprehensible like this…
/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/
…then you’ve seen regular expressions in action.
If you want to do things like replace a word throughout text for another word, see if a bit of text contains a specific phrase, or count how many times a specific pattern appears through text, those are the types of things where regular expressions are dynamite.
Without further ado, five basic ideas for spicing up your Rails code.
Tip 1: More Interesting Typography
You can use this technique to spice up your website’s typography — with ligatures and more interesting ampersands to be precise.
If you’re on a Mac, you can use the character palette to see some of the ligatures on your system.
Certain letter combinations just fit next to other in cool ways. These are known as ligatures.

Mostly prevalent in print design, they’re not nearly as common in web design. However, we can change that a tiny bit. Many common ligatures in print design include glyphs such as ff and fi and ft and so-forth. Unfortunately, not all commonly installed fonts include these ligatures. For language reasons the ae and oe combination are present in many typefaces, so I will give those examples.
I also I want to spice up my titles with really pretty ampersands, a technique that I first really noticed on Jon Tan’s wickedly awesome website.
This is code that goes in the view. I’m just adding a format_title helper method to the normal link_to method.
<%= link_to format_title(@featured.title), individual_feature_url(@featured) %>
This is the code that goes in the Application helper file. I made it an application helper so I could easily use it throughout a project. However, if you only want it on the homepage or a particular section, you’d put it in a different helper.
def format_title(the_title)
the_title.to_s.
gsub(/&/, "&“).
gsub(/ae/, “æ”).
gsub(/AE/, “Æ”).
gsub(/OE/, “Œ”).
gsub(/oe/, “œ”)
end
The helper takes the title, turns it into a string, and uses a sequence of Ruby global substitution methods to wrap ampersands in special span elements and change any OE and AE letter combinations into the appropriate html character codes.
Here is the CSS for spicing up the ampersand.
span.amp {
font-family: "Baskerville", "Goudy Old Style", "Palatino", "Book Antiqua", serif;
font-style: italic;
}
You can of course go even fancier if you want.
The end result is you’ve changed this normal looking title on a website.
…to this much more unique and extraordinary title without any ongoing-effort.
Pretty neat to see the oe and ae ligatures in action along with much prettier ampersands.
Tip 2: Category replacement in text
Let’s say you were building a recipe website, and you wanted to link to the meat or egg or milk categories on every user submitted recipe. Expecting the user to do this is a bit much, so we’re going to automate this process.
First you can add this bit of code to your controller’s show method. This grabs all of your keywords and puts them in an instance variable you can use.
def show
@keywords = Keyword.find(:all)
end
And finally, we have a helper that uses Ruby’s substitution method to change the first instance of any keyword term into a link to the appropriate category. (I call it keywords throughout my code.)
def add_keywords(the_text)
@keywords.each do |keyword|
the_text.to_s.sub!(/\b#{keyword.keyword}\b/i, "#{keyword.keyword}“)
end
In your view, you just use the add_keywords helper.
So you can change something like this….
This is a random recipe I just randomly typed out. In real life, I’m a semi-decent cook. Note that the extra style observed here comes from the CSS first-letter and first-line pseudo-elements.

…to this, all automatically linked without any extra effort.

There are many ways you can spice this up further, but this is one basic way to automatically generate links throughout anything. Make stuff easier to find and automate everything possible and your users will love you!
Tip 3: Grammar shortcuts
One thing that drives grammarians/typographers nuts is the use of a hyphen instead of an em dash. You can read more about the differences between these characters here and here.
On a Mac, pressing shift-option-minus produces an em dash.
I constantly forget the sequence of characters necessary to produce an em dash, so I want a quick shortcut to automatically change an easy to remember bit of text into an em dash.
Here’s the helper
def format_article(the_text)
the_text.to_s.gsub(/--/, "—")
end
So two hyphens next to each will automatically be changed into an em dash. And that’s a lot easier to remember than the keyboard combination to
You can of course think of more ways to add proper grammar to your site. There are many tiny grammatical things you can do to spice up your app.
Tip 4: Better Validations
Rails provides an awesome group of validations for data right out of the box — validates_presence_of, validates_uniqueness_of, validates_numericality_of, etc.
If you need data entered in a specific format though, regex can really help you out.
For instance, in a Story model, you could add this extra validation to ensure that only legitimate URLs are entered into the database.
class Story < ActiveRecord::Base
validates_format_of :url, :with => /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$/ix
end
That makes life easier.
Tip 5: Using the blocks
I’m not 100% sure about the Perl comment because I’ve only ever used a tiny bit of Perl in college in a distributed systems class and it’s been ages since I’ve ever seriously worked with any of that code.
Many examples that I’ve seen don’t mention the existence of this syntax, nevertheless using regex with blocks is possible, which (I’m pretty sure) distinguishes it slightly from Perl and some other languages.
For instance, this simple helper uses the global substitution method of ruby to take any appearance of the word “backwards”, reverse it, and make it lower-case. Yes, this example is sort of pointless. But it does illustrate that you have a lot of potential power at your fingertips to take text, scan it, and think of other neat things to do with it.
def format_article(the_text)
the_text.to_s.gsub(/backwards/i) {|s| s.reverse.downcase}
end
Conclusion
I’ve just touched on the basics of a few simple examples. You can probably improve them significantly.Nevertheless, using regular expressions is an extraordinarily powerful programming technique that can allow you to do amazing things if you just sit down and think out of the box a little.
Posted on May 4th, 2008 by Chris Papadopoulos.
Subscribe to the RSS feed, Trackback, or contact me privately.
Chris Papadopoulos (5 comments.) @ May 4
Wordpress was incorrectly configuring a lot of the code. If anything looks wonky, please let me know.
Just out of curiosity, would anybody reading this be able to recommend a Wordpress technique or plugin for automatically making prettier source code?
Thanks and enjoy.
James Edward Gray II (1 comments.) @ May 15
Using regular expressions in Tips 1 and 3 is kind of like clubbing someone to death with a loaded Uzi.
The issue is that you aren’t using any regex features, so firing up the regex engine for each of those substitutions is a lot of unneeded work. You can just use String replacement instead and save a lot of overhead (for example: the_text.to_s.gsub(”–”, “–”)).
Also, Perl can use arbitrary code in place of a replacement string. You append the /e option to turn on this functionality.
Chris Papadopoulos @ May 15
The main message and intent of the article was to encourage thinking about how you can creatively work with text to achieve interesting results, not necessarily to provide polished code examples that you’d want to use in every situation in production.
Thanks for the thoughtful comment James.