2012-09-16 18 views
0

我現在正在提一個提及功能,所以當用戶輸入@時,他們爲用戶名鍵入的下一個部分是可點擊的,直到出現空格。這是假設他們正確輸入用戶名,只有字母和數字。我需要它工作,所以如果他們輸入「Hi @jon!」它會將感嘆號(或任何不是字母或數字的符號)視爲不屬於用戶名的一部分,並將其排除在外,而不僅僅是查找以下空間。Ruby on Rails字符串:找到不是字母或數字的下一個字符?

這是我有:

while @comment.content.include? "@" do 
    at = @comment.content.index('@') 
    space = @comment.content.index(' ', at) 
    length = space - at 
    usernotag = @comment.content[at + 1,length - 1] 
    userwtag = @comment.content[at,length] 
    @user = User.where(:username => usernotag.downcase).first 
    @mentioned_users.push(@user) 
    replacewith = "<a href='/" + usernotag + "'>*%^$&*)()_+!$" + usernotag + "</a>" 
    @comment.content = @comment.content.gsub(userwtag, replacewith) 
end 

@comment.content = @comment.content.gsub("*%^$&*)()_+!$", "@") 

任何想法,我應該怎麼辦呢?

回答

1

您應該使用正則表達式解析/提取用戶參考:

# Transform comment content inline. 
@comment.content.gsub!(/@[\w\d]+/) {|user_ref| link_if_user_reference(user_ref) } 
@comment.save! 

# Helper to generate a link to the user, if user exists 
def link_if_user_reference(user_ref) 
    username = user_ref[1..-1] 
    return user_ref unless User.find_by_name(username) 

    link_to user_ref, "https://stackoverflow.com/users/#{user_name}" 
    # => produces link @username => /user/username 
end 

這裏假設像你說的(字母或數字)您的用戶名被限制於字母數字字符。如果您有其他角色,則可以將它們添加到正則表達式中包含的集合中。

相關問題