ruby で外部プログラムを利用する.

 ruby から外部プログラムを利用する方法として,IO クラスの popen メソッドを使うか,Open3 ライブラリを使う方法があるようだ.後者は入出力ストリームを指定できる.

 これらを利用すると,前回の記事の swf2xml と xml2swf は以下のように書き直せる.

  # _target_ :: Path of swf template.
  # Return value :: String of xml.
  def swf2xml(target)
    return IO.popen("swfmill -e cp932 swf2xml #{target} stdout") {|io| io.read }
  end

  require "open3"
  # @xml is string of xml.
  # Return value :: Binary of swf.
  def xml2swf
    bin = ""
    Open3.popen3("swfmill -e cp932 xml2swf stdin stdout"){|stdin, stdout|
      stdin.puts @xml
      stdin.close
      bin = stdout.read
    }
    return bin
  end

これで要求ごとに一時ファイルを書き出すようなめんどくさいことをせずに,外部プログラムの出力結果を取得できる.勉強になった.