我正在Ruby On Rails中创建一个Twitter克隆,我如何对它进行编码,以便’推文’中的’@ …’变成链接?

我有点像一个Rails新手,所以请耐心等待我,除了这一部分,我已经找到了大部分应用程序。

def linkup_mentions_and_hashtags(text) text.gsub!(/@([\w]+)(\W)?/, '@\1\2') text.gsub!(/#([\w]+)(\W)?/, '#\1\2') text end 

我在这里找到了这个例子: http : //github.com/jnunemaker/twitter-app

辅助方法的链接: http : //github.com/jnunemaker/twitter-app/blob/master/app/helpers/statuses_helper.rb

也许您可以使用正则表达式查找“​​@ …”然后用相应的链接替换匹配项?

您可以使用正则表达式搜索@sometext {whitespace_or_endofstring}

你可以使用正则表达式,我不知道ruby,但代码应该几乎完全如我的例子:

 Regex.Replace("this is an example @AlbertEin", "(?[@#])(?\\w{1,}[^ ])", "${type}${nick}"); 

这个例子会回来

 this is an example 
		      	

也许您可以使用正则表达式来解析以@开头的单词,然后使用正确的链接更新该位置的字符串。

这个正则表达式将为您提供以@符号开头的单词,但您可能需要调整它:

 \@[\S]+\ 

我也一直在努力,我不确定它是100%完美,但它似乎工作:

  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 

我将它与一些谷歌搜索拼凑在一起,并在api文档中阅读String.scan。