LoginSignup
5
8

More than 3 years have passed since last update.

【RSS】記事引っ張ってニュースアプリ作ってみた①モデル作成~タスク処理まで

Last updated at Posted at 2019-05-17

RSSを用いて記事を外部から取得する方法でオリジナルニュースアプリを作成。
忘れないように処理ごとに分けて自分用に記録。
使うモデルは2つ(feedモデル→記事カテゴリー/entryモデル→記事)

①feedモデル作成 (RSSのURL(カテゴリー別)を入れておく用)

$rails g model feed name url description:text 
$rake db:migrate

②entryモデル作成(取得する記事が更新されていくモデル)

$rails g model entry title published:datetime content:text url author feed_id:integer
$rake db:migrate

③アソシエーションを定義 (親:feed, 子:entry)

feedモデル

has_many :entries, dependent: :destroy

entryモデル

belongs_to :feed

④feedモデルにカテゴリをあらかじめ設定してしまう(仮データ作成用にgem 'seed_fu'使用)

db/fixtures/development/feeds.rb

Feed.seed do |s|
  s.name ="Today"
  s.url ="http://rss.--------------.xml"       ※記事URLを指定
  s.description ="Today"
end

⑤gem 'feedjira'をインストール

⑥記事を取得するためのrakeタスク作成 (modelにあらかじめ登録していたURLから取得できるように!)

lib/task/news_rakeに以下を記述

namespace :news do
  task feeds: [:environment] do
    Feed.all.each do |feed|
      content = Feedjira::Feed.fetch_and_parse feed.url
      content.entries.each do |entry|
        local_entry = feed.entries.where(title: entry.title).first_or_initialize
        local_entry.update_attributes(content: entry.content, author: entry.author, url: entry.url, published: entry.published)
        p "Newsed Entry - #{entry.title}"
      end
      p "Newsed Feed - #{feed.name}"
    end
  end
end


※だがしかし、、、これだと反応しない!
gem 'feedjira'の仕様が変わって、fetch_and_parseのfetch部分が働いてないようだ・・・。
[参考URL]https://github.com/feedjira/feedjira
ということで、gemを使って記事を引っ張ってくるようにする。

⑦gem 'httparty'をインストール(これで記事持ってこれる!)

namespace :news do
  task feeds: [:environment] do
    Feed.all.each do |feed|
      xml= HTTParty.get(feed.url).body
      content = Feedjira::Feed.parse xml
      content.entries.each do |entry|
        local_entry = feed.entries.where(title: entry.title).first_or_initialize
        local_entry.update_attributes(content: entry.content, author: entry.author, url: entry.url, published: entry.published)
        p "Newsed Entry - #{entry.title}"
      end
      p "Newsed Feed - #{feed.name}"
    end
  end
end

⑧タスク実行

$rails db:migrate:reset
$rails db:seed_fu
$rake news:feeds

[RSS機能実装参考URL] http://www.tom08.net/entry/2017/01/04/160933

5
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
8