Steve
Steve

Reputation: 4566

How to identify and make a link out of '@' in user comments like they do on Youtube

I want to look into making functionality like Youtube has on their website when a user types in a comment and if they have something like '@username' the system recognizes the '@' sign and makes a link to the username's comments. I'm developing using Rails 3 but any information regarding about the logic required for this feature would be appreciated, thanks.

EDIT: Additonal question: Where's the best place to put the logic for this? I would feel like the controller would be so if a client doesn't have javascript it'll still work.

Upvotes: 1

Views: 111

Answers (1)

mridula
mridula

Reputation: 3281

I am sure there are multiple (and even better) ways of doing this. How I did it was -

A function to parse the input string: I wrote a helper function -

  1. It traversed every word in the post and for all words starting with an '@'
  2. For every such word it checked if the user existed in the application.
  3. If yes then replace the word with a link to the user profile.
  4. Write the new post (one with the links) to the database.

    def mention_users_and_tags(post)
        post_with_user_links = ""
        words = post.message.split
        words.each do |word|
            if word[0] =~ /^@.*/ and word.length > 1
                if extract_user_if_exists(word[1,word.length-1])
                    post_with_user_links << "#{link_to "#{word}", :controller => "users", :action => "show", :id => @mentioned_user.id} "
                else
                    post_with_user_links << word << " "
                end
            end
        end
    end
    

EDIT - I think this method should be written in the model and called in the controller. This was the first time I was coding in rails, so I wasn't very sure where everything goes and I wrote this as a helper function. But now I know all business logic goes in the Model. Since mentioning users in posts can be considered part of the business logic, I'd write a function for it in the model.

Upvotes: 3

Related Questions