[ruby] TumblrAPIのモジュールを作った。

巷で話題のシンプルblogツールTumblr。複雑になっているblogの無駄な機能を削ぎ落としシンプルでなかなかいいです。
これ、個人用のメモにつかえないかなぁと思ったのですがメモをいちいちwebブラウザ開いて書くのは面倒くさいとなぁ思いました。
そこでhttp://tumblr.com/api/apiを見付けたのでrubyから叩くためにモジュールをつくってみました。

ソース

require 'net/http'
require 'uri'

module Tumblr
  module API
    class WriteError < StandardError; end
    class Write
      TUMBLR_API_URI = URI.parse('http://tumblr.com/api/write')
      
      def initialize(email, passwd)
        @email = email
        @password = passwd
      end

      def post(type, title, body)
        data = make_data(type, title, body)
        http_post(TUMBLR_API_URI, data)
      end
      
      private
      def make_data(type, title, body)
        "email=#{@email}&password=#{@password}&type=#{type}&title=#{title}&body=#{body}"
      end
      
      def http_post(url, data)
        res = Net::HTTP.start(url.host, url.port) do |http|
          http.post(url.path, data)
        end
        raise WriteError.new("Bad email or password") if res.code == '403'
        res
      end
    end
  end
end

テスト

require 'sample'
require 'test/unit'

class Test_Tumblr < Test::Unit::TestCase
  def setup
    @tumblr_write = Tumblr::API::Write.new('your-email', 'password') #各自書き換え
    @tumblr_write_dummy = Tumblr::API::Write.new('hoge@bar.baz', 'foo')
  end

  def test_post
    assert_equal '201', @tumblr_write.post('regular', 'hello!!', 'world!!').code
  end

  def test_posterror
    assert_raises(Tumblr::API::WriteError){ @tumblr_write_dummy.post('regular', 'hello!!', 'world!!') }
  end
end

使いかた

ほとんどテストのまんまです。

tumbler = Tumblr::API::Write.new('your-email', 'password')
tumbler.post('regular', 'title', 'body')

今のところpost typeのうちregularしか対応していません。メモとして使いたかったので。
ほかにもphoto、quote、link、conversation、video等あるので対応させてgemに上げます。

ChangelogをパースしてTumblrにpostなんかおもしろいかなぁと思ってます:-)