Want clean code? Stop using the editor. 1
Recently I was adding some accessors to a ruby class on the fly, and I kept getting confused by this block:
eval <<-EOF
def #{mode.underscore.gsub(' ', '_')}
return self.additional_fields[:payment_modes]["#{mode.underscore.gsub(' ', '_')}".to_sym]
end
EOF
The code isn’t particularly complicated, just creating a quick accessor to get at the underlying hash. Yet I had a couple bugs simply because without the editor to give me hints, the code was that much harder to follow. This turns out to be a blessing in disguise, as I am forced to write extremely clean code just to keep from confusing myself. Opening up the String class cleans this up a bit, and removes duplication:
eval <<-EOF
def #{mode.rubify}
return self.additional_fields[:payment_modes]["#{mode.rubify}".to_sym]
end
EOF
There much better. So the next time you think your code isn’t as clear as it could be, or maybe if you think it’s perfect, try reading it without any syntax highlighting. If you can still follow it quickly and easily, then maybe it doesn’t entirely suck.
I’m not sure I understand why you need string eval for this - in perl I’d be writing something like
*{$mangled_mode} = sub { my $self = shift; $self->additional_fields ->{payment_modes} ->{$mangled_mode}; };and the $mangled_mode variable would be lexically captured by the sub {} block - can’t you use a similar closure trick to clean up the ruby?