→ define_method and rdoc
03 August 2009
Seen in evented-memcache-client:
# Wish these could be properly rdoc'd...
%w(flush_all version quit).each { |cmd|
class_eval do
define_method "#{cmd}" do
book_it(cmd.to_sym)
send_to_peer "#{cmd}\r\n"
end
end
}
I used to write a lot of Ruby code like this. define_method is there – why not use it, right?
Remember, though: write code that is easy to read. Here’s how I would rewrite the above to be rdoc friendly:
def flush_all; send_command(:flush_all) end
def version; send_command(:version) end
def quit; send_command(:quit) end
def send_command(cmd)
book_it(cmd)
send_to_peer "#{cmd}\r\n"
end
Just like that it’s rdoc friendly, has less nesting, and is still easy to modify.