使用推送器仅向朋友推送消息
Using Pusher to push messages to friends only
我已经在基于模型Post的Rails应用程序上设置了基本的Pusher功能,但Pusher更新会发送给所有用户,而我希望只有与发件人"有联系/朋友"的用户才能看到更新。
在视图中使用javascript还是ruby最好地解决这个问题?从控制器,我通过Pusher发送@post.user_id到视图,但在实现以下内容时,我似乎无法使其工作:
后控制器
def index
# Get the current user's friends
@friends = current_user.friends.all
end
end
def create
@post = current_user.posts.new(post_params)
@puserid = @post.user_id
@postuser = User.find_by_id(@puserid)
@userslug = @postuser.slug
@ids = current_user.friends.pluck(:id) << current_user.id
if @post.save
#flash[:success] = "You have created a new post"
redirect_to posts_path
Pusher['worklink'].trigger('update', {
postcontent: @post.content,
userid: @post.user_id,
userslug: @userslug,
userfirstname: @postuser.firstname,
userlastname: @postuser.lastname,
postid: @post.id
})
else
render "new"
end
end
后索引视图
<script src="https://js.pusher.com/2.2/pusher.min.js"></script>
<script type="text/javascript">
var pusher = new Pusher('<%= Pusher.key %>'); // uses your API KEY
var channel = pusher.subscribe('worklink');
channel.bind('update', function(data) {
var prependLink = "<a href='/profile/" + data.userslug + "'>" + data.userfirstname + " " + data.userlastname + " " + "</a><span class='red small'>New</span>";
var user = data.userid;
$("#comments").prepend(
"<% if @friends.include?(" + user + ") %><div class='post_box'><div class='post'><p class='username'><b>" + prependLink + "</b></p><p class='post_content'>" + data.postcontent + "</p><div class='post_attributes'><ul><div class='right'><li class='small bold'>0 </li><li class='x'><a data-method='post' href='/home/" + data.postid + "/likes' rel='nofollow'><img alt='Tick2' src='/assets/tick2.png'></a></li></div><li class='post_time'>less than a minute ago</li></ul></div></div></div><% end %>");
$('.post p:contains("http://")').html(function(index, html) {
var url = html.match(/(((ftp|https?):'/'/)['-'w@:%_'+.~#?,&'/'/=]+)|((mailto:)?[_.'w-]+@(['w]['w'-]+'.)+[a-zA-Z]{2,3})/g);
$.each(url, function(i, v) {
html = html.replace(v, '<a href="' + v + '" target="_blank">' + v + '</a>');
});
return html;
});
});
</script>
有三种不同的通道类型(http://pusher.com/docs/client_api_guide/client_channels):
- 私人
- 公共
- 存在
我想最适合你的是存在,它需要在订阅前进行身份验证,你可以控制是否允许订阅。
此外,您可以参考此代码以获得更多功能示例:https://github.com/tarnfeld/PusherChat-Rails
相关文章:
- Ajax聊天消息重复而不仅仅是更新
- 如果localstorage为空,则显示欢迎消息
- 绑定时将Parsley minlength消息作为选项传递时,未对其进行自定义
- 离开页面时弹出消息
- 我需要为我的朋友在这个项目上提供帮助
- 有没有一种方法可以在控制台关闭的情况下让console.log()在IE中记录消息
- 消息显示之外的淘汰验证
- 选项卡侦听器未被来自后台脚本的消息激活
- jQuery在输入下验证post错误消息
- Scipt未在选定选项卡中执行以发送和接收消息
- 检查xmlhttprequest问题的消息
- AngularJs对ng消息的自定义替换
- KIK机器人在用户许可后向用户的朋友发送消息
- 在Facebook中向用户发送通知的邀请朋友消息
- 给朋友发消息,我想知道Javascript API
- 向不是你朋友的facebook用户发送消息
- 使用推送器仅向朋友推送消息
- 向多个朋友发布故事/消息'feed/Wall
- 当我的用户收到朋友的未读消息时,我如何切换我的网站标题
- 发送消息到选定的fb朋友使用facebook javascript sdk