views:

468

answers:

7

I am somewhat of a Rails newbie so bear with me, I have most of the application figured out except for this one part.

A: 

Perhaps you could use Regular Expressions to look for "@..." and then replace the matches with the corresponding link?

Nebakanezer
thanks, I will give that a try.
Cody Brown
A: 

You could use a regular expression to search for @sometext{whitespace_or_endofstring}

ZeissS
A: 

You can use regular expressions, i don't know ruby but the code should be almost exactly as my example:

Regex.Replace("this is an example @AlbertEin", 
                    "(?<type>[@#])(?<nick>\\w{1,}[^ ])", 
                    "<a href=\"http://twitter.com/${nick}\"&gt;${type}${nick}&lt;/a&gt;");

This example would return

this is an example <a href="http://twitter.com/AlbertEin&gt;@AlbertEin&lt;/a&gt;

If you run it on .NET

The regex (?<type>[@#])(?<nick>\\w{1,}[^ ]) means, capture and name it TYPE the text that starts with @ or #, and then capture and name it NAME the text that follows that contains at least one text character until you fin a white space.

AlbertEin
A: 

Perhaps you can use a regular expression to parse out the words starting with @, then update the string at that location with the proper link.

This regular expression will give you words starting with @ symbols, but you might have to tweak it:

\@[\S]+\
Kaleb Brasee
A: 

You would use a regular expression to search for @username and then turn that to the corresponding link.

I use the following for the @ in PHP:

$ret = preg_replace("#(^|[\n ])@([^ \"\t\n\r<]*)#ise", 
                    "'\\1<a href=\"http://www.twitter.com/\\2\" >@\\2</a>'", 
                    $ret);
Cesar
A: 

I've also been working on this, I'm not sure that it's 100% perfect, but it seems to work:

  def auto_link_twitter(txt, options = {:target => "_blank"})
    txt.scan(/(^|\W|\s+)(#|@)(\w{1,25})/).each do |match|
      if match[1] == "#"
        txt.gsub!(/##{match.last}/, link_to("##{match.last}", "http://twitter.com/search/?q=##{match.last}", options))
        elsif match[1] == "@"
          txt.gsub!(/@#{match.last}/, link_to("@#{match.last}", "http://twitter.com/#{match.last}", options))
          end
    end
    txt
  end

I pieced it together with some google searching and some reading up on String.scan in the api docs.

Dan McNevin
+1  A: 
def linkup_mentions_and_hashtags(text)    
  text.gsub!(/@([\w]+)(\W)?/, '<a href="http://twitter.com/\1"&gt;@\1&lt;/a&gt;\2')
  text.gsub!(/#([\w]+)(\W)?/, '<a href="http://twitter.com/search?q=%23\1"&gt;#\1&lt;/a&gt;\2')
  text
end

I found this example here: http://github.com/jnunemaker/twitter-app

The link to the helper method: http://github.com/jnunemaker/twitter-app/blob/master/app/helpers/statuses_helper.rb

magnushjelm
This works perfectly. Thanks so much.
Cody Brown