Rire とは?
このブログにちょくちょくでてくる Rire について、簡単に説明しておきます。
それに、今改良を重ねていて、何だか軸がぶれているような気がして、
自分の中にある完成イメージをもとに、README を書きます。
残しておけば、この先、役に立つはず。
Rire とは?
一応、スクレイピングライブラリです。
個人目的で作り始めたWeb データ収集や、Web ラジオのリンク収集、ダウンロードをしたいな、
と思ったのがきっかけです。あと、Ruby の勉強も。
同じようなライブラリに scrapi などがありますけれど。
Step0. データを用意する
今回は以下の XML データからデータを抽出します。
<root> <title>extract test</title> <record> <item> <name>user01</name> <date>2007/11/25</date> <comment>comment01 foobar</comment> </item> <item> <name>user02</name> <date>2007/11/28</date> <comment>comment02 foobar</comment> </item> <item> <name>user03</name> <date>2007/11/30</date> <comment>comment03 foobar</comment> </item> </record> </root>
Step1. プロパティを定義する
Rire::PropertyBase のサブクラスとして Foo を定義する。
Foo には、データの抽出条件とそのデータに付ける名前を定義します。
class Foo < Rire::PropertyBase record :regexp => '<item>(.+?)</item>' do has_property :name, :regexp => '<name>(.+?)</name>' has_property :date, :regexp => '<date>(.+?)</date>' has_property :comment, :regexp => '<comment>(.+?)</comment>' end end
Step2. データを解析する
クラスメソッド fetch に解析したいデータを渡して、
解析結果の戻り値を受け取ります。
foo = Foo.fetch(DATA.read) foo.each do |entry| puts "name: #{entry.name}" puts "date: #{entry.date}" puts "comment: #{entry.comment}" end
出力結果
user01, 2007/11/25, comment01 foobar
user02, 2007/11/28, comment02 foobar
user03, 2007/11/30, comment03 foobar
StepX. 機能を追加したい
ただのクラスなので、以下のように module にメソッドを書いて、
include するなり、extend すれば、抽出クラスを量産しつつ、
プラグインみたいに機能を追加できます。
module RirePlugins def to_rss(options) rss = RSS::Maker.make('2.0') do |maker| maker.channel.title = options[:title] maker.channel.description = options[:description] maker.channel.link = options[:link] self.each do |entry| item = maker.items.new_item item.title = entry.title item.link = entry.link item.description = entry.description item.date = entry.date end end open(options[:filename], 'w') do |fout| fout.puts rss end end end