Cleaning up imports in jRuby
August 13th, 2009
Import Puts Noise In My Class
Today I stumbled accross something like this:
class SwtBuilder
import org.eclipse.swt.widgets.Display
import org.eclipse.swt.widgets.Shell
import org.eclipse.swt.widgets.Button
import org.eclipse.swt.widgets.Canvas
import org.eclipse.swt.SWT
import ch.mollusca.foo.Bar
import ch.mollusca.foo.Jiffy
def build
puts SWT::BOLD | SWT::ITALIC
end
end
SwtBuilder.new.build
Alas, jRuby doesn’t support
import org.eclipse.swt.widgets.*there is plenty of noise throughout this class definition. It’s a lot of vertical clutter and I don’t like it. This will even get worse for any class that ties together a few java classes.
Enter Importer
I tried to figure out a way to clean this up. Maybe I’ve hit the spot, but I think it’s not quite there yet. Anyway:
module Importer
module ClassMethods
def importer(hash)
unless hash[:path] && hash[:items]
puts "need to specify path and items!"
else
hash[:items].each do |item|
path = hash[:path] + "." + item
import path
end
end
end
end
def self.included(receiver)
receiver.extend ClassMethods
end
end
This allows me to write:
class SwtBuilder
include Importer
importer :path => 'org.eclipse.swt.widgets', \
:items => ['Display', 'Shell', 'Button', 'Canvas']
importer :path => 'org.eclipse.swt', :items => ['SWT']
def build
puts SWT::BOLD | SWT::ITALIC
end
end
SwtBuilder.new.build
It’s formatted in two lines for layout reasons, but in principle can nicely be written on one line. Any comments on the idea?
Leave a Reply
You can use Textile markup in your comments!