Archive for category Ruby

Object.const_getをハックした話

大変厳しい監視にも負けず、普通にRubyの話をします。

文字列のクラス名をクラスにするには、Rubyの場合evalとかもあるけれど(参照: Class.forNameはどう書くのか、コメントも)、 Object.const_get を使うのが一番安全な気がします。変なコードをねじ込まれてもNameErrorになるだけですし。

irb(main):001:0> Object.const_get("String")
#=> String
irb(main):002:0> Object.const_get("String").new
#=> ""

でもこれ、たとえば Net::HTTP みたいな名前空間付きのクラスを呼ぶとエラーになりますんよ。

irb(main):001:0> require 'net/http'
=> true
irb(main):002:0> Object.const_get("Net::HTTP")
NameError: wrong constant name Net::HTTP
	from (irb):2:in `const_get'
	from (irb):2

なので、以下のようなメソッドをつくりました。

nested_const_get.rb

1
2
3
4
5
6
7
8
9
10
class Object
  def self.nested_const_get(*args)
    stack = (args[0] =~ /::/) ? args[0].split("::") : args
    klass = Object
    while const = stack.shift
      klass = klass.const_get(const)
    end
    klass
  end
end
irb(main):001:0> require 'nested_const_get'
#=> true
irb(main):002:0> Object.nested_const_get("String")
#=> String
irb(main):003:0> require 'net/http'
#=> true
irb(main):004:0> Object.nested_const_get("Net::HTTP")
#=> Net::HTTP
irb(main):005:0> Object.nested_const_get("Net::HTTP").start("blog.udzura.jp", 80)
#=> #<Net::HTTP blog.udzura.jp:80 open=true>
irb(main):006:0> Object.nested_const_get("Net::HTTP::Get")
#=> Net::HTTP::Get
irb(main):007:0> Object.nested_const_get("Net::HTTP::Get::METHOD")
#=> "GET"

ハックというほどでもないですね。一応、何かの役に立つこともあろうかと。

経過報告(某ライブハウスのスケジュールをパース)

休みなので,何かを作っています。

その中間生産物として,以下のようなスクリプトを作りました。

1
./o_summary.rb

ってやると,2010年3月(とりあえず決め打ち)のO-GROUPのライブ予定をまとめて表示してくれます。

udzura@ubuntu-vaio:~/dev$ ./o_watch_test.rb
@@@O-East@@@
●2010年3月01日 @ O-East
□テリアの東 「空のエチュード II」
Dichten
ソノダバンド/WADAIKO龍鼓会/COKEBOTTLE
#dicline/LIVING IN THE DARK
ゲスト:C’est La Vie
開場17:30/開演18:00●前売3000/当日3500●ドリンク別
問合せ:03-5458-4681 O-EAST
Dichten
=> http://shibuya-o.com/category/east/?id=schedule&Year=2010&Month=3#post-9701

----
●2010年3月02日 @ O-East
□PUNK ROCK CONFIDENTIAL JAPAN presents PUNKAFOOLIC! KOTTONMOUTH KINGS JAPAN TOUR
KOTTONMOUTH KINGS
開場19:00/開演20:00●前売5000/当日未定●ドリンク別
発売中●ぴあ(344-442)・ローソン(70471)・e+
※未就学児童入場不可
問合せ:03-3475-9999 H.I.P
http://www.punkafoolic.com/

=> http://shibuya-o.com/category/east/?id=schedule&Year=2010&Month=3#post-8977

----
●2010年3月03日 @ O-East
□美神降臨〜LIV MOON FIRST CLUB SHOW
LIV MOON
開場18:00/開演19:00●前売5500/当日未定●ドリンク別
発売中●ぴあ(345-509)・ローソン(74305)・e+・CN
問合せ:03-3462-6969 クリエイティブマン

=> http://shibuya-o.com/category/east/?id=schedule&Year=2010&Month=3#post-9126

----
●2010年3月04日 @ O-East
□たむらぱん パンタスティックツアー
たむらぱん
開場19:00/開演19:30●前売4500/当日5000●ドリンク別
発売中●ぴあ(342-160)・ローソン(78625)・e+・CN
問合せ:03-3498-9999キョードー東京

=> http://shibuya-o.com/category/east/?id=schedule&Year=2010&Month=3#post-8702

----
●2010年3月05日 @ O-East
□おわらないせかいのうたいかた
……

Read the rest of this entry »

Rubyで色を判断(適当バージョン)

色コード「#RRGGBB」をパースして,適当でいいので何色か判断するクラスを作りたい。ちょっとしたアレで使用したいので。

最初に思いついたもの

やっつけなのでろくにテストも書いていない。。

Read the rest of this entry »