开发者

Rails - News Feed

Alright here's the trickiest question I've ever had to ask on StackOverflow.

My Web App allows creating a document. This document is automatically saved lets say ever couple of seconds.

Meanwhile, I want a news feed to lets users know what there friends are up to. So I created a observer开发者_如何学编程 model which after_create creates a news_feed type item.

Problem is this observer as is now will create a news_feed on ever save which is a huge firehose.

So I want to make it so the news_feed for this model is only injects per session or every X minutes. So I added a last_feeded_at column to the model.

Problem is when I try to update that field in the observer to mark it was feeded, that triggers the observer, which makes a mess of everything.

What's the best way to handle this? I'm open to all smart suggestions.

Thanks


I would not add an attribute to you Document model for this. You probably have something like this already:

class Document
  has_many :news_feeds, :order => 'created_at DESC'
end

In your callback (in Document model), just check when the last news_feed was created:

after_save :create_news_feed, :if => Proc.new { |doc| doc.news_feeds.first.created_at <= 10.minutes.ago }

This will only call create_news_feed if the last news_feed was created at least 10 minutes ago.


I assume that when the user finishes editing they perform a final save? Define a attr_accessor, draft, which is sent as a parameter from the controller when handling request.js ajax saves. I don't see need for an observer really; just put it in the model.

attr_accessor :draft
after_save :log_unless_draft

def log_unless_draft
  unless draft.eql?(true)
    log_event.new(...

By the way, I don't understand why after_create is even triggering, given these aren't new_record?s beyond the first save.


I'd create your NewsFeed object using this kind of logic

def find_or_create_feed
  if session[:news_feed].nil?
    NewsFeed.new
  else
    NewsFeed.find(session[:news_feed])
  end
end

that way, you can return the same NewsFeed object for an entire session. If you want to get fancy and expire it, do a sweep of the news_feeds table periodically to remove feeds over a given age.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜