From: Ross Bamford Date: 2006-10-30T02:02:37+09:00 Subject: Re: Interesting trival example of why open classes are good? Hi, On Sun, 2006-10-29 at 16:45 +0900, Peter Michaux wrote: > Does anyone have an interesting, standalone example > showing the utility of open classes in under 30 lines? under 20? The example below probably isn't what you're after, but as David said it's pretty tricky to justify open classes in a self-contained example this short. It's just over 30 lines. One other good example of their usefulness springs to mind though - I've seen a few projects (I think RCov is one, though I could be wrong) that have an extension replace some of their 'default' (ruby-implemented) methods with ones implemented in C, for better performance or integration. Obviously the benefit being that, if you can support the native extension you get the improvements, but if not you can still use the pure-ruby implementation, without changing your code at all. Anyway, here's the (contrived) example: #!/usr/bin/env ruby class User def initialize(name, email) @name, @email = name, email end attr_accessor :name, :email end class Instrument class << self def on_call(clz, imethods = clz.instance_methods) clz.class_eval do imethods.each do |m| unless m =~ /^__/ alias_method "__uninst_#{m}", m define_method(m) do |*args| r = __send__("__uninst_#{m}", *args) yield(self, m, args, r) r end end end end end end end Instrument.on_call(User, [:initialize, :name, :email]) do |slf, name, args, r| puts "#{slf}.#{name} (#{args.inspect}) => #{r.inspect}" end u = User.new("billy", "billy@example.com") puts "Username is: #{u.name}" puts "Email is : #{u.email}" puts "Uninst name: #{u.__uninst_name}" -- Ross Bamford - rosco@roscopeco.REMOVE.co.uk