50 lines
1.2 KiB
Ruby
50 lines
1.2 KiB
Ruby
require "pp"
|
|
class Feed < ActiveRecord::Base
|
|
has_many :items
|
|
|
|
validates_uniqueness_of :url
|
|
|
|
default_scope where(:has_errors => false)
|
|
scope :with_error, unscoped.where(:has_errors => true)
|
|
|
|
def fetch!
|
|
Feedzirra::Feed.fetch_and_parse(url,
|
|
:on_success => lambda do |url, feed|
|
|
feed.entries.each do |entry|
|
|
unless Item.exists?(:url => entry.url)
|
|
entry.sanitize!
|
|
items << Item.create_from_feed_entry!(entry)
|
|
end
|
|
end
|
|
by_url(url).update_attribute(:has_errors, false)
|
|
end,
|
|
:on_failure => lambda do |url, response_code, response_header, response_body|
|
|
by_url(url).update_attribute(:has_errors, true)
|
|
end
|
|
)
|
|
end
|
|
|
|
def self.import(url, *params)
|
|
Feedzirra::Feed.fetch_and_parse(url,
|
|
:on_success => lambda do |url, feed|
|
|
Feed.create!(:url => feed.feed_url, :title => feed.title).fetch!
|
|
end,
|
|
:on_failure => lambda do |url, response_code, response_header, response_body|
|
|
if params.first.include?(:force)
|
|
Feed.create!(:url => url, :has_errors => true)
|
|
end
|
|
end
|
|
)
|
|
end
|
|
|
|
def self.update_all!
|
|
Feed.all.each do |feed|
|
|
feed.fetch!
|
|
end
|
|
end
|
|
|
|
private
|
|
def by_url(feed_url)
|
|
Feed.where(:url => feed_url).first
|
|
end
|
|
end
|