Jim Weirich -- Advanced Ruby Class Design

Transformers 2007-12-20
Jim Weirich 是rake,builder等作者,他在做<<Advanced Ruby Class Design>>演讲的时候,列出了一段很漂亮的代码,
在此提供给大家分享,供大家学习,Jim Weirich可是骨灰级的programmer哟

# BlankSlate provides an abstract base class with no predefined
# methods (except for <tt>\_\_send__</tt> and <tt>\_\_id__</tt>).
# BlankSlate is useful as a base class when writing classes that
# depend upon <tt>method_missing</tt> (e.g. dynamic proxies).
#
class BlankSlate
  class << self
    
    # Hide the method named +name+ in the BlankSlate class.  Don't
    # hide +instance_eval+ or any method beginning with "__".
    def hide(name)
      if instance_methods.include?(name.to_s) and
        name !~ /^(__|instance_eval)/
        @hidden_methods ||= {}
        @hidden_methods[name.to_sym] = instance_method(name)
        undef_method name
      end
    end

    def find_hidden_method(name)
      @hidden_methods ||= {}
      @hidden_methods[name] || superclass.find_hidden_method(name)
    end

    # Redefine a previously hidden method so that it may be called on a blank
    # slate object.
    def reveal(name)
      bound_method = nil
      unbound_method = find_hidden_method(name)
      fail "Don't know how to reveal method '#{name}'" unless unbound_method
      define_method(name) do |*args|
        bound_method ||= unbound_method.bind(self)
        bound_method.call(*args)
      end
    end
  end
  
  instance_methods.each { |m| hide(m) }
end

yanghuxiao 2009-02-11
不错,学习了。
Global site tag (gtag.js) - Google Analytics