Importer v0.2
August 22nd, 2009
Danlucraft pointed something out the other day: Why would Importer require that you use a hash? And of course he was right. So after a little review: Importer, second iteration:
module Importer
module ClassMethods
def importer(package, classes)
classes.each do |item|
path = package + "." + item
import path
end
end
end
def self.included(receiver)
receiver.extend ClassMethods
end
end
This will remove the pesky hash notation:
require 'importer'
class Banzaiii
include Importer
importer 'org.eclipse.swt.widgets', \
%w{Display, Shell, Button, Canvas}
importer 'org.eclipse.swt', ['SWT']
def build
puts SWT::BOLD | SWT::ITALIC
end
end
Maybe this will evolve into something that enables you to do the follwing:
class Widgets include Importer importer 'org.eclipse.swt.widgets.*' end # and thus canvas = Widgets::Canvas.new
Which is exactly what is currently missing from jruby…
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?