如何在mongoid中每3分钟下载一次feed_entries

时间:2014-12-11 11:23:46

标签: ruby-on-rails mongoid whenever feedjira

我有两个模型source.rb和feed_entries.rb。如何每3分钟下载一次feed_entries。  我曾经尝试过宝石'无论什么时候'并收到错误NoMethodError:私有方法`select'

source.rb

class Source
  include Mongoid::Document
  include Mongoid::Timestamps

  field :url, type: String
  field :title, type: String
  field :site, type: String

  after_save :load_feed_entries

  has_many :feed_entries, dependent: :destroy

  def load_feed_entries
    last_entry = self.feed_entries.last
    if last_entry.nil?
      feed = Feedjira::Feed.fetch_and_parse(self.url)
    else
      feed = Feedjira::Feed.fetch_and_parse(self.url,
        :if_modified_since => last_entry.published_at.to_time)
    end

    Source.add_entries(feed.entries, self.id)
  end

  def self.update_all_feeds(urls)
    Feedjira::Feed.fetch_and_parse(urls,
      :on_success => lambda { |url, feed|
        rss = Source.select("sources.id").where(:url => url).first
        Source.add_entries(feed.entries, rss.id)
      }
    )
  end

  private
    def self.add_entries(entries, stream_id)
      entries.each do |entry|
          unless  FeedEntry.where(guid: entry.id).exists?
            FeedEntry.create!(
              :name          => entry.title,
              :summary       => entry.summary,
              :url           => entry.url,
              :content       => entry.content,
              :published_at  => entry.published,
              :guid          => entry.id,
              :source_id => stream_id,
            )
          end
      end
    end
end

feed.rake

task :collect => :environment do
  urls = Source.select("sources.url").all.map { |v| v[:url] }
  Source.update_all_feeds(urls)
end

1 个答案:

答案 0 :(得分:0)

source.rb

  def self.update_all_feeds(urls)
    Feedjira::Feed.fetch_and_parse(urls,
      :on_success => lambda { |url, feed|
        rss = Source.only(:id).where(:url => url).first
        Source.add_entries(feed.entries, rss.id)
      }
    )
  end

feed.rake

task :collect => :environment do
  urls = Source.only(:url).all.map { |v| v[:url] }
  Source.update_all_feeds(urls)
end