委譲といえばForwardable
method_missingとfind_by_xxx - LukeSilvia’s diary
method_missingは多くの場合デバッグが困難になるので乱用厳禁。あくまで最終手段にすべき。DRbのように相手が得体の知れないオブジェクトならばmethod_missingは有効だが、よくわかってるオブジェクト相手には基本的にmethod_missingは使用すべきではない。
Userクラスを読んだときに、取り得るメソッドの集合が一目でわからないところが気持ち悪い。
俺ならForwardableで明示的に転送する。
require 'forwardable' class User attr_reader :name,:age,:type,:profile def initialize(args) @name = args[:name] @age = args[:age] @type = args[:type] @profile = args[:profile] end extend Forwardable def_delegators :@profile, :school, :company end
method_missingをdefine_methodに置き換える話 - http://rubikitch.com/に移転しました
Jay Fields' Thoughts: Ruby: Replace method_missing with dynamic method definitions
そういや前に同じようなこと書いたなぁ…
require 'forwardable' class Decorator extend Forwardable def initialize(subject) @subject = subject (class << self; self; end).class_eval do def_delegators :@subject, *subject.public_methods(false) end end end
思い付いたのでdefine_methodぢゃなくてdef_delegatorsで書き換えてみる。Paul and Aliさんも同じようなコードを思い付いてコメントに書いてあった。考えることは一緒なんだな…