开发者

ruby auto link username

What would be a good way to "auto link" words with @ i开发者_运维知识库n front of them like twitter does? For example auto_link_user('Hello @matt please send file to harry@gmail.com') would return 'Hello @matt please send file to harry@gmail.com'

I'm trying to do exactly this in Ruby http://www.ideone.com/aGklx


str = "@foo, I'm @bar. My email is bar@bar.com"
r = /(^|\s)@([a-z0-9_]+)/i

str.gsub(r){|x| "#{$1}<a href=\"http://wwww.twitter.com/#{$2}\">@#{$2}<a/>"}
#=> "<a href=\"http://wwww.twitter.com/foo\">@foo<a/>, I'm <a href=\"http://wwww.twitter.com/bar\">@bar<a/>. My email is bar@bar.com" 

Using String#gsub


If you're looking for direct linking into Twitter (it's not clear from your question if this is what you're trying to do) then you should look at their @anywhere API.

EDIT: You could then, instead of doing it in ruby, do what you want to do with Javascript on the client side:

<script type="text/javascript">
    twttr.anywhere(function (T) {
        T("#linkify-this-content").linkifyUsers();
    });
</script>

It's not exactly what you were looking for, it seems, but it's an option.


generalize way with base url,

def append_urls str, base_url

str.gsub!(/(^|\s|\b)@([a-z0-9_]+)/i) do |word|
  word = $2
"<a href='#{base_url}#{word}'>#{word}</a>"
end

end

add this method to one of helper and invoke in view as

  <%= append_urls(str_to_append_url,"www.twitter.com/") %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜