名言を使いたい。

大好きなWebサービスの1つに
http://meigen.o-bit.biz/
という名言を共有するサービスがあります。
このサイトには素晴らしい名言がたくさんあって
いつもエネルギーをもらっています。
中身のコンテンツを使わしてもらいたいなーと思ったんだけど、
APIとかないし、スクレイピングさせてもらいますた。

#!/usr/bin/env ruby

require 'open-uri'
require 'nokogiri'
require 'yaml'

URL = 'http://meigen.o-bit.biz/meigens'

meigen = Array.new

(1..64).each do |p|
  page = Nokogiri::HTML(open("#{URL}?p=#{p}"))

  word_path = page.xpath('//h2[@class="featurette-heading"]/a')
  author_path = page.xpath('//span[@class="author"]')

  word_path.zip(author_path).each do |w, a|
    meigen << %W(#{w.text.gsub(/(\r\n|\r|\n)/, '')} #{a.text})
  end

end

puts meigen.to_yaml
$ ruby scrape_meigen.rb > ./data/meigen.yml

こんな感じでもってきました。

生成したyamlファイルを使うときは

require "yaml"

class Meigen
  MEIGEN = YAML.load_file(File.expand_path(File.join('../', 'data', 'meigen.yml'), __FILE__))

  def initialize
    @meigen = MEIGEN.sample
  end

  def word
    @meigen.first
  end

  def author
    @meigen.last
  end
end

meigen = Meigen.new

p meigen.word
p meigen.author

とかやれば、ランダムに名言と誰が言ったか返してくれる。

みんな名言好きだし、gemにして配布したいなんておもったけど、どうなんだろ。

とりあえず、毎朝チャットにbotで流そうと思います。
ありがとう。名言の中の人。