poファイルにメッセージを抽出するためのパーサを独自に追加する

ruby-gettext-howto-poparser

Ruby-GetText-Package-2.1.0から

[Back]

Ruby-GetText-1.8.0からpoファイルのmsgidを抽出するためのパーサを独自に追加できるようになりました。ここでは、そのパーサの書き方、使い方を紹介します。

パーサを書く

パーサモジュールを宣言し、target?, parseという2つのメソッドを実装します。最後に、そのパーサをGetText::RGetTextに登録します。

require 'gettext/rgettext'
module TestParser
  module_function
  # 与えられたファイルがこのパーサで処理すべきかどうか
  # を判断します。処理する場合はtrue、そうでなければfalseを返します。
  def target?(file)
    File.extname(file) == '.glade'
  end
  # 実際のパース結果を返します。
  # fileにはパースするファイル名が入ります。
  # 戻り値は、PoMessageの配列にします。
  def parse(file)
   :
   # ここがメインとなるロジックです。複雑になるかもしれませんね。
   ary = []
   # Simple message
   po = PoMessage.new(:normal)
   po.msgid = "hello"
   po.sources = ["foo.rb:200", "bar.rb:300"]
   po.add_comment("Comment for the message")
   ary << po
   # Plural message
   po = PoMessage.new(:plural)
   po.msgid = "An apple"
   po.msgid_plural = "Apples"
   po.sources = ["foo.rb:200", "bar.rb:300"]
   ary << po
   # Simple message with the message context
   po = PoMessage.new(:msgctxt)
   po.msgctxt = "context"
   po.msgid = "hello"
   po.sources = ["foo.rb:200", "bar.rb:300"]
   ary << po
   # Plural message with the message context.
   po = PoMessage.new(:msgctxt_plural)
   po.msgctxt = "context"
   po.msgid = "An apple"
   po.msgid_plural = "Apples"
   po.sources = ["foo.rb:200", "bar.rb:300"]
   ary << po
   return ary
  end
end
# パーサの登録
GetText::RGetText.add_parser(TestParser)

上記をtestparser.rbという名前で保存します。

使ってみる

rgettextと一緒に使う

まずはrgettextと一緒に使ってみましょう。

$ rgettext -rtestparser targetfiles1.rb targetfiles2.rb ....
-o foo.pot

Rakeと一緒に使う

Rakeと一緒に使うのも簡単です。require 'testparser'をupdatepoタスクの中で行うだけ。

desc "Update pot/po files."
task :updatepo do
  require 'gettext/utils'   #testparser.rbの内部で呼び出してもいいかも。
  require 'testparser'
  GetText.update_pofiles("myapp", Dir.glob("app/**/*.{rb,rhtml}"), "myapp 0.0.1")
end

ChangeLog

  • 2006-12-19 初版作成 - Masao