Hi,
On Sun, 2006-10-29 at 16:45 +0900, Peter M. 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”, “[email protected]”)
puts “Username is: #{u.name}”
puts “Email is : #{u.email}”
puts “Uninst name: #{u.__uninst_name}”