LoginSignup
43
48

More than 5 years have passed since last update.

【Ruby】RSSを取得し、DBに保存してみる

Last updated at Posted at 2014-01-29

元記事

下記エントリの転載になります。
【Ruby】RSSを取得し、DBに保存してみる - rokuro Fire

前提

・mysqlを利用
・DBの接続情報を外部ファイル(database.yml)にまとめてある
・ActiveRecordを利用
・インサート処理はBULK INSERT

RSSの取得

RSSを取得して、その情報をDBに入れてみます。

getrss.rb
require 'date'
require 'rss'
require 'mysql2'
require 'active_record'
require 'activerecord-import'

# database.ymlにDB接続情報を記述
# ActiveRecordを利用
config = YAML.load_file('database.yml')
ActiveRecord::Base.establish_connection(config)
class Item < ActiveRecord::Base
    # バリデーションの記述など
    validates_presence_of :title
    validates_presence_of :link
    validates_uniqueness_of :link
end

class manageRss
    def getrss
        insertData = []
        lists = [
            'http://www.rsslist1.com/xml',
            'http://www.rsslist2.com/xml'
        ]
        return false unless lists

        lists.each do |rss|
            rssdata = RSS::Parser.parse(rss)

            begin
                rssdata.items.each do |entry|
                    # dateの記述が間違っているRSSがたまにあるので念のため
                    tmpdate = entry.respond_to?(:pubDate) ? entry.pubDate : entry.dc_date
                    item = Item.new
                    item.title = entry.title
                    item.link = entry.link
                    item.entrydate = tmpdate
                    insertData << item
                end
            rescue => e
                # エラー時の処理
            end
        end

        # BULK INSERT
        Item.import insertData
        return true
    end
end

DBからデータを取得

上記でDBに入れたデータを取得してみます。

main.rb
# ActiveRecordを利用

def showrss
    @items = Item.all.order("entrydate DESC").limit(100)
end

上記処理にSinatraを組み合わせれば、簡単にRSSリーダーサイトを作ることができます。
こちらの記事も合わせてどうぞ。

43
48
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
43
48