This post originated from an RSS feed registered with Ruby Buzz
by Red Handed.
Original Post: My Favorite Bad Practices
Feed Title: RedHanded
Feed URL: http://redhanded.hobix.com/index.xml
Feed Description: sneaking Ruby through the system
I can’t truthfully say what level of coder I am. I mean there are moments when I’d say I’ve got an awfully brilliant nugget of code on my hands, but who knows. Brilliant code is sort of hard to notice when you’re chuggin along, you know?
I definitely have some sordid moments. Wanting to finish, wanting to sprint, I yank out one of the following constructs. Bits of code I’m not proud of, but which I love with forbidden love, which must be prefixed with a moment of knuckle-cracking.
1. Using rescue as an exception-catching or.
So, it’s common to use or in assignment, right? You often see stuff like this:
tmpdir = ENV['TMP'] || "/tmp"
If the environment variable isn’t set, then tmpdir will fall back to "/tmp". Perfectly honorable bit of code.
But lately, when my primary data source is possibly volatile (a database or a file or something), I use rescue in place of or.
It feels seedy, ignoring all the possible exceptions that could be thrown deep in the API, but sometimes I just don’t care. I’ll deal with it elsewhere.
2. Going puts all over the place.
I’ll be in the middle of a web application using puts. See, I just used it so much in command-line apps that I just always end up overriding Kernel::puts or redirecting STDOUT when the script starts. It’s totally lacksa lazy, huh?
class << STDOUT
def write( msg )
unless defined? @puts_log
require 'logger'
@puts_log = Logger.new '/tmp/my-script.log', 'monthly'
end
@puts_log.info msg
end
end
3. Using ERb for everything.
After this weekend, all my C unit tests for Syck are now driven by an ERb template. It totally works, I love it, it’s perfect—it’s a hack. Load YAML n Ruby. Generate C with Ruby. Then make check. Lotsa three-point turns.