Rails Notes: At or Reply to Someone

Posted by Lawrence Sun on 2014-11-09

1. At

The ‘@’ function is used widely on web apps.

Here I use a jquery plugin called atwho. First download jquery.atwho.js, jquery.caret.js, jquery.atwho.css. Then add these files to app/assets.

Add //= require jquery.atwho to app/assets/javascripts/application.js and add *= require jquery.atwho to app/assets/stylesheets/application.css.scss.

Then use it to at users when replying a comment. Following happycasts, bind the textarea like this:

1
2
3
4
5
6
7
8
9
10
11
$(function(){
var commenter = [];
var commenter_exist= [];
$('.comment-user').each(function() {
if($.inArray($(this).text(), commenter_exist) < 0){
commenter.push($(this).text());
commenter_exist.push($(this).text());
}
});
$('textarea').atwho({at:"@", 'data':commenter});
});

One problem I found was this atwho funciont didn’t work until refreshed this page. When I deleted turoblink, it worked fine. So Finally I solved it by using a gem called jquery.turbolinks.

2. Reply

Sometimes we would like to reply to other’s comment. When we click reply button, we want to ‘@’ this comment’s author.

Thanks to Campo app, I added reply function to my own rails app.

Add following parts to comments view.

1
2
3
<a class="btn", data-reply-to="@<%= comment.user.name %> " >
<i class="fa fa-reply"></i>
</a>

Then include a coffee javascript file. Remember to set corrosponding class/id in the html file.

1
2
3
4
$(document).on 'click', '.comments [data-reply-to]', ->
textarea = $('#new_comment textarea')
textarea.focus()
textarea.val(textarea.val() + $(this).data('reply-to'))