【Ruby】send, class_evalを使ったモックオブジェクト
■topic summary
study about "send"
この本を読んでます。
Rubyベストプラクティス -プロフェッショナルによるコードとテクニック
- 作者: Gregory Brown,高橋征義,笹井崇司
- 出版社/メーカー: オライリージャパン
- 発売日: 2010/03/26
- メディア: 大型本
- 購入: 9人 クリック: 307回
- この商品を含むブログ (48件) を見る
勉強しても勉強してもねー。。。
send を使ったプライベート呼び出し
class User; end user = User.new singleton = class << user; self; end singleton.send(:define_method, :hoge){"bingo"} p user.hoge #<= "bingo"
本には
define_method で定義したメソッドは特異クラス上でプライベートになるので、利用するためにはsend()が必要になる
とあるけど、
class_eval でも実現できるよね?
class User; end user = User.new singleton = class << user; self; end singleton.send(:define_method, :hoge){"bingo"} singleton.class_eval{define_method(:foo){"bar"}} p user.hoge #<= "bingo" p user.foo #<= "bar"
うむうむ。
どっちでもいいのかな。
define_methodの引数
class String send(:define_method, :hoge) do |a| p a*3 end end "".hoge("c") #<= "ccc"
send で渡したブロックはそのまま引き渡される。
オブジェクトのメソッド name を args を引数に して呼び出し、メソッドの実行結果を返します。
http://docs.ruby-lang.org/ja/1.9.3/method/Object/i/send.html
ブロック付きで呼ばれたときはブロックもそのまま引き渡します。
ちょっとややこしかったのでメモ。