Jason Meridth

I am a continuously learning senior full stack SDE/SRE trying to not let best be the enemy of better.

Using gsub to wrap substring

10 Sep 2009 » »

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 JasonMeridth.com. 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')
    begin
      status = Twitter.user(user_id).status['text']
      status ||= ''
      status = status.gsub(/http://(.+?)s/) do |url|
        " <a href='#{url}' target='_blank'>#{url}</a> "
      end
    rescue Exception => e
      logger.info("Twitter Helper Exception: " + e)
      status = ""
    end
  end
end

and then in my view I just call:

latest_twitter_status

The important part of code to look at is:

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

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