自分の興味の赴くままにIT技術系のネタを取りとめもなくメモっています。
Ruby言語やLinuxのネタが多いです。
Ruby言語やLinuxのネタが多いです。
October 19, 2004 [おもひで]
■ [Ruby] pseudoiconv.rb
WindowsのOne-Click Installer等の一部の環境ってiconvが入ってなかったりする。
#最新版ならば入ってるかも。
そんな環境でもRuby/GLib2をインストールできる環境(つまりはWin32の環境なんだけどさ)用にpseudoiconv.rbというGLib.convertを使ってIconv.iconvをシミュレートするスクリプトを書いてみた。
エラーは全部Iconv::IllegalSequenceになっちゃうんだけどね。
begin
require 'iconv'
rescue LoadError
begin
require 'glib2'
module Iconv
class IllegalSequence < ArgumentError; end
module_function
def iconv(to, from, str)
begin
GLib.convert(str, to, from).split(//)
rescue
raise IllegalSequence.new(str)
end
end
end
rescue LoadError
module Iconv
module_function
def iconv(to, from, str)
warn "Iconv was not found." if $DEBUG
str.split(//)
end
end
end
end
■ ちなみに次期リリース版のRuby/GLib2では以下のようにもうちょっとだけエラー処理をIconvに近づけることができる予定。
begin
require 'iconv'
rescue LoadError
begin
require 'glib2'
module Iconv
class InvalidEncoding < ArgumentError; end
class IllegalSequence < ArgumentError; end
class InvalidCharacter < ArgumentError; end
module_function
def iconv(to, from, str)
begin
GLib.convert(str, to, from).split(//)
rescue GLib::ConvertError => e
case e.code
when GLib::ConvertError::NO_CONVERSION
raise InvalidEncoding.new(str)
when GLib::ConvertError::ILLEGAL_SEQUENCE
raise IllegalSequence.new(str)
else
raise InvalidCharacter.new(str)
end
end
end
end
rescue LoadError
module Iconv
module_function
def iconv(to, from, str)
warn "Iconv was not found." if $DEBUG
str.split(//)
end
end
end
end
■ require 'iconv'しているアプリは、iconvの代わりにこれを使っておけば、もしかしたらちょっとだけアプリケーションの適用プラットフォームが広がるかもしれない。
■ さらにnkfやuconv等を試すようなコードにすれば日本語関連では結構なところまでいけそうな気がする。uconvはともかくnkfはRubyに標準添付されてるしね。
■ 次のRuby-GetText-Packageはこの仕組みを利用しようかと考え中。

Iconvのエラーは、一括して捕まえられるようにIconv::Failureをincludeしてます。
なるほど。includeしてるかどうかまでは意識してませんでした。情報ありがとうございます。