Los Techies : Blogs about software and anything tech!

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 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.
Kick It on DotNetKicks.com
Posted Sep 10 2009, 03:56 PM by Jason Meridth

Comments

Twitted by lostechies wrote Twitted by lostechies
on 09-10-2009 5:13 PM

Pingback from  Twitted by lostechies

Copyright Los Techies 2008, 2009. All rights reserved.
Powered by Community Server (Commercial Edition), by Telligent Systems