tomatomax.net

Every rule has its exception.

Archive for the Ruby Category

uninitialized constant Class::YAML (NameError)

自宅サーバのアップデートを行ったのだけれども、そのあといつの間にかBotが止まっていた。いつもはcronで動かしているけど、手動で実行してみると以下のエラー。

/usr/lib/ruby/gems/1.8/gems/twitter4r-0.3.0/lib/twitter/console.rb:23:in `from_config’: uninitialized constant Class::YAML (NameError)

とりあえずエラーメッセージでぐぐってみると、以下の記事がヒット。

environment.rb uninitialized constant when starting console

この記事に書いてあるとおり、require ‘yaml’を追加することで無事復活。今は反応するようになってます

さくらサーバにWWW::Mechanizeをインストール

さくらインターネットのサーバでこのブログを運用しているわけですが、せっかくサーバを借りてみたのでRubyスクリプトを動作させたい!

でもWWW::Mechanizeが入ってません><

rubygemも入ってません(こっちはまあ当然か)

さくらのレンタルサーバーに RubyGems をインストールする手順を参考に、rubygemをインストール。ここまでは問題なし。

続けてmechanizeのインストールに取り掛かったのだけれども、こっちは失敗。

%gem18 install nokogiri
Building native extensions. This could take a while…
ERROR: Error installing nokogiri:
ERROR: Failed to build gem native extension.

/usr/local/bin/ruby18 extconf.rb install nokogiri
checking for #include … no
libxml2 is missing. try ‘port install libxml2′ or ‘yum install libxml2′
*** extconf.rb failed ***
(略)

libxml2がないそうです。自分のサーバなら、書いてあるようにyumでインストールするところなんだけど、当然できません。なので、ユーザフォルダにlibxml2を展開してみる。
The XML C parser and toolkit of Gnomeからlibxml2をダウンロード。prefixにユーザフォルダを指定してインストールします(UserNameを自分のユーザ名に置き換える)

%./configure –prefix=/home/UserName
%make
%make install

あとはインストールしたヘッダを読むように指定してmechanizeのインストール

%gem18 install mechanize — –with-opt-include=/home/UserName/include/libxml2
Building native extensions. This could take a while…
Successfully installed nokogiri-1.2.1
Successfully installed mechanize-0.9.2
2 gems installed
Installing ri documentation for nokogiri-1.2.1…
Installing ri documentation for mechanize-0.9.2…
Installing RDoc documentation for nokogiri-1.2.1…
Installing RDoc documentation for mechanize-0.9.2…
%

今度は成功。ページも取得できているみたい。

net/imapでGMailのメールを取得

自動でfollowするように、GMailに届いたfollow通知からユーザ名を取り出してみる。IMAPでやってみた版。

参考:katoy: cocolog: ruby で gmail (imap) にアクセスする練習

require 'net/imap'

followers = []
username = "hoge"
password = "hogehoge"

port = 993
usessl = true

begin
imap = Net::IMAP.new("imap.gmail.com", port, usessl)
p imap.greeting
imap.login(username, password)
imap.examine("inbox")
imap.fetch(1..-1, "ENVELOPE").each do |f|
messageNo = f.seqno
subject = f.attr["ENVELOPE"].subject
to_mailbox = f.attr["ENVELOPE"].to[0].mailbox
if to_mailbox == "hoge+bot" && # To:がhoge+bot@gmail.comのものを取り出す
/is now following you on Twitter/ =~ subject
imap.fetch(messageNo, "RFC822").each do |m|
# ユーザ名を得る
if /http:\/\/twitter\.com\/(\w+)/ =~ m.attr["RFC822"]
p $1
followers << $1
end
end
end
end
followers.each { |u|
follow(u)
}
p "success"
rescue
p "failed"
end