This article was migrated from http://rails.office.drecom.jp/takiuchi/archive/163
Rubyのダックタイピングを活用して、シンプルかつ汎用的な
Stringパーサ&コンバータstring_to.rbを書いてみました。
このコードは、to_xxxx_xxxxメッセージを受け取り、
XxxxXxxx#parse(self)を呼び出すことで
自分自身をXxxxXxxxに変換する
method_missingハンドラをStringクラスに付け加えます。
class String
def method_missing(method, *arg, &block)
method_name = method.to_s
if method_name.slice!(0..2) == "to_"
method_name.gsub!(%r(__), '::_')
method_name.camelize.constantize.parse(self, *arg, &block)
else
super
end
end
end
利用方法:
上のコードをコピーして、
$:の通った場所にstring_to.rbとして保存し、
そしてこの機能を使いたいところからrequireします。
require 'date'
require 'uri'
require 'string_to'
"2007-2-11".to_date #=> Date.parse(self)
"http://www.drecom.co.jp/".to_URI #=> URI.parse(self)
[English]
POSTSCRIPT:
constantizeやcamelize等のRails依存のメソッドを
書き直して、RubyForgeにプロジェクトを登録しました。
string-to
これでようやく、いつものようにgemコマンドでインストールできるようになりました。
$ sudo gem install string-to
使い方は以下のとおり:
require 'rubygems'
require 'string_to'
require 'date'
"2007-2-13".to_date # => Date.parse("2007-2-13")
parseメソッドを実装しているクラスやモジュールは意外と多いですね。
CGI、Date、Name、Ripper、URI、Time、YAML、JSON、CGI::Cooki
e...
次のバージョンでは、parseメソッドがあったら便利なモジュールにparseを追加するのをやろう。
This article was migrated from http://rails.office.drecom.jp/takiuchi/archive/163