Twitter's mention feature for Rails26 Feb 2017
I’ve uploaded a sample Twitter style app that you guys can find on my github. It’s based off Michael Hartl’s Ruby on Rails tutorial which I highly recommend if you’re just starting out with Ruby on Rails. Just follow the readme on Github to try it out.
gem 'jquery-atwho-rails' and
gem 'redcarpet' to your Gemfile then do a
To begin with you’ll need to add a markdown function to the application_helper, this function will be used by the view to render your mention, decorated with markdown. Redcarpet has a tonne of options and several different renderers that you can choose to enable, below is my setup.
Now you can render content anywhere throughout your application with markdown applied, by simply passing the markdown function your content like this.
Next you’ll need to add this to your routes.rb file. This route is used to fire an AJAX request that will return a list of users, with usernames matching the characters typed into the text area. I’ve added this function to the users_controller for simplicity.
With the routing in place you can add the following code to your users_controller.rb, you’ll notice that Mention.all is being passed a param, more on that in a bit .
Now you can add an after_create callback on your Post model called add_mentions, this will be invoked after the creation of any new posts.
Finally the Mention class, this class will contain all the logic for finding and creating our mentions. Some of you might be thinking “why bother with a Mention class when you could just add this functionality to the User model”. I extracted the functionality to this class for several reasons:
- It’s important to follow the single responsibility principle, this helps prevent ActiveRecord models from growing too complex and becoming a maintenance nightmare.
- It clearly defines the mention concept within the application.
- With this design it’s easy to extend the functionality of the feature further.
In my day job the mention feature was popular with the users working on our systems. They asked if I could extend the feature so they could mention teams as well as users. With this design it’s easy to add another subclass to the Mention class, I added a class called TeamMention to mention teams. So now instead of having a simple username mention we have a polymorphic mention for both teams and users.
Let me know in the comment’s or on Twitter if you have any questions, comments or a creative implementation of the feature!