Using gsub to wrap substring

Over my lunch today I finally had an opportunity to use something I learned yesterday reading Dan Croak’s “gsub with a block” post on the Thoughtbot blog.

I use the twitter gem and just display my last status on my personal homepage at I didn’t want to hand out my username and password so all I do is encapsulate the twitter piece in a module called TwitterHelper and put it into my app/helpers/ folder in my Rails application:

require 'twitter'
require 'pp'

module TwitterHelper  
  def latest_twitter_status(user_id='armmer')
      status = Twitter.user(user_id).status['text']
      status ||= ''
      status = status.gsub(/http://(.+?)s/) do |url|
        " <a href='#{url}' target='_blank'>#{url}</a> "
    rescue Exception => e"Twitter Helper Exception: " + e)
      status = ""

and then in my view I just call:


The important part of code to look at is:

status = status.gsub(/(http://.*)/) do |url|
  " <a href='#{url}' target='_blank'>#{url}</a> "

This code will wrap any strings that start with http:// with an html href.

About Jason Meridth

Continuously learning software developer trying to not let best be the enemy of better
This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

Comments are closed.