ターミナルの出力をtumblrに送るスクリプト

昔からアカウントだけ作ってたんですが、なんとなく一昨日ぐらいからtumblrを使い始めました。
で、昨日rails勉強会やってる最中に、railsコマンドの結果とかtumblrに送れれば良いなあと思い、
標準入力をtumblrに送るrubyスクリプト書いてみました。


コードは

#!/usr/bin/env ruby

require 'net/http'
require 'cgi'
require 'yaml'
require 'optparse'

class TerminalTumblr
  def initialize
    Net::HTTP.version_1_2
    option_parse
    set_options
  end

  def option_parse
    @option_parameter = Hash.new
    opt = OptionParser.new
    opt.on("-c", "--configfile=CONFIGFILE") {|v| @configfile = v }
    opt.on("-t", "--title=TITLE") {|v| @option_parameter[:title] = v }
    opt.on("-e", "--email=EMAIL") {|v| @option_parameter[:email] = v }
    opt.on("-p", "--password=PASSWORD") {|v| @option_parameter[:password] = v }
    opt.on("-d", "--debug") {|v| @debug = true}
    opt.parse(ARGV)
  end

  def set_options
    @configfile ||= File.join(File.dirname(__FILE__), "config.yaml")
    yaml = YAML.load(File.read(@configfile))
    account = yaml["account"] || Hash.new
    account.each do | key, value | 
      @option_parameter[key.to_sym] ||= value
    end
    @postparameter = yaml["postparameter"] || Hash.new
  end

  def to_query_parameter(hash)
    hash.map{|i| i.map{|j| CGI.escape j.to_s}.join('=') }.join('&')
  end

  def set_params(params) 
    @params = params
    @option_parameter.each do | key, value | 
      @params[key.to_sym] ||= value
    end
    @postparameter.each do | key, value | 
      @params[key.to_sym] ||= value
    end
  end

  def post(params)
    set_params(params)
    Net::HTTP.start("www.tumblr.com", 80) do |http|
      response = http.post("/api/write", to_query_parameter(@params))
      p response if @debug
    end
  end
end


terminal_tumblr = TerminalTumblr.new
params = Hash.new
params["type"] = "regular"
params["body"] = STDIN.read
terminal_tumblr.post(params)

と、こんな感じです。
アカウントを設定したスクリプトファイルが必要で
スクリプトをおいたディレクトリと同じ場所に

account: 
  email: xxxx@xxxx.xxx
  password: xxxxxxxxxx

というようなファイルをオプションで指定しない限りはconfig.yamlという名前で置く必要があります。


というわけで、
cat terminaltumblr.rb |./terminaltumblr.rb -t test
とやると
http://zenpou.tumblr.com/post/379708460/test
のようになります。


オプションで、-tでタイトル付けられたり、yaml上にpostparameterとしてtitleとか設定すると、
常にタイトル付ける様な機能もつけてみました。

account: 
  email: xxxx@xxxx.xxx
  password: xxxxxxxxxx

postparameter: 
  title: terminal


そんだけ。


参考サイト: TumblrAPIをRubyから使う - Ruby Study Go