Skip to content

Instantly share code, notes, and snippets.

@ainame
Created January 1, 2012 17:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ainame/1547882 to your computer and use it in GitHub Desktop.
Save ainame/1547882 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
# RubyBestPracticeに載っている書き方
# 以下の解説ページを参照
# http://www.mapee.jp/ruby/post_66.html
class BlockRun
def initialize
@handlers = { }
end
def handle(message, &block)
puts message
@handlers[message] = block
end
def run
puts "run"
@handlers.each do |message, block|
puts "run:"+message
block.call("@")
end
end
def self.run(&block)
puts "self.run"
br = BlockRun.new
br.instance_eval(&block)
br.run
end
end
=begin
br = BlockRun.new
br.handle("hoge"){〜〜}
br.handle("hoge2"){〜〜}
でも良いが....
=end
# DSLっぽくかけて,ブロック内に処理を収められる
# BlockRun.run実行時にはblock内の処理は評価されず,
# instance_evalで実行する
BlockRun.run do
handle("1") { puts "handle1" }
handle("2") { puts "handle2" }
handle("3") { puts "handle3" }
end
__END__
出力結果
[sandbox]> ruby block_run.rb
self.run
1
2
3
run
run:1
handle1
run:2
handle2
run:3
handle3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment