Sunday, April 22, 2007

API unickifying with JRuby


So I've been putting together some code examples for RubyCodeCamp in Columbus in a couple weeks. Quite awhile back I ran into a situation where I wanted to read an Excel spreadsheet from Ruby. At the time, there was no good way to do it in Ruby (MRI) and so I used Java and the nifty POI library. I thought this might be make for a nice example in JRuby. So I fired up jirb and started coding. In a few minutes I was reading data from a spreadsheet:


require 'java'

require '/home/ccnelson/java/poi/poi-2.5.1-final-20040804.jar'

include_class 'org.apache.poi.poifs.filesystem.POIFSFileSystem'

include_class 'org.apache.poi.hssf.usermodel.HSSFWorkbook'
include_class 'org.jruby.util.IOInputStream'

File.open("/home/ccnelson/documents/Invoice15.xls") do |f|
workbook = HSSFWorkbook.new(IOInputStream.new(f))
puts "cell 0,0: #{workbook.getSheetAt(0).getRow(0).getCell(0).getStringCellValue}"

end


There's some nice stuff going on. I really like being able to just include a jar and start using it. Still, using the POI API in Ruby looks rather icky -- (actually, it started even worse than this, but Charles Nutter was on #jruby and was kind enough to tell me about IOInputStream). After looking at this code for a minute I started thinking and it came to me: "Hey this is Ruby. We can do anything we want!"

I started with that ugly getStringCellValue at the end. It would be nice if we could give cell a to_s and do away with that. Well, guess what, since this is Ruby, I can just open HSSFCell and do it:



require 'java'

require '/home/ccnelson/java/poi/poi-2.5.1-final-20040804.jar'

include_class 'org.apache.poi.poifs.filesystem.POIFSFileSystem'
include_class 'org.apache.poi.hssf.usermodel.HSSFWorkbook'
include_class 'org.jruby.util.IOInputStream'

include_class 'org.apache.poi.hssf.usermodel.HSSFCell'

class HSSFCell
def to_s
getStringCellValue
end
end

File.open("/home/ccnelson/documents/Invoice15.xls") do |f|
workbook = HSSFWorkbook.new(IOInputStream.new(f))
puts "cell 0,0: #{workbook.getSheetAt(0).getRow(0).getCell(0)}"

end




Cool! Even though HSSFCell is a java class, because I am using it from JRuby I can open it up and stick methods on it. This got me excited. What do I really want this API to look like? I think I'd really rather be able to access my spreadsheet cells using a simple 2 dimenional array. I mean, that's really what they are for my purposes. And guess what? In Ruby, the [] operator, like everything else in Ruby, is just a method. And if it's just a method, well I can abuse... err.. bend it to my own nefarious purposes. Bwah ha ha hah ha hah ha ha..

Oops, got a little carried away there. Ruby coding will do that sometimes. Back to the task at hand:



require 'java'

require '/home/ccnelson/java/poi/poi-2.5.1-final-20040804.jar'

include_class 'org.apache.poi.poifs.filesystem.POIFSFileSystem'
include_class 'org.apache.poi.hssf.usermodel.HSSFWorkbook'
include_class 'org.jruby.util.IOInputStream'

include_class 'org.apache.poi.hssf.usermodel.HSSFCell'

include_class 'org.apache.poi.hssf.usermodel.HSSFRow'
include_class 'org.apache.poi.hssf.usermodel.HSSFSheet'

class HSSFCell
def to_s
getStringCellValue
end

end

class HSSFSheet
def [] (index)
getRow index
end
end

class HSSFRow

def [] (index)
getCell index
end
end
File.open("/home/ccnelson/documents/Invoice15.xls") do |f|
workbook = HSSFWorkbook.new(IOInputStream.new(f))
spreadsheet = workbook.getSheetAt(0)
puts "cell 0,0: #{spreadsheet[0][0]}"

end



Nice! This for me is one of the killer features of JRuby. A lot of scripting languages will let you access the Java APIs in a more light weight language. But because of the features of the Ruby language, it becomes so easy to modify APIs to suit your needs, desires, and insane urges.

15 comments:

AndrewO said...

API eunuchifying?!?! What?!

Very helpful stuff. I just thought about doing this instead of trying to get the POI-Ruby bindings to work. I'm glad to see someone else has done the initial work. Thanks for the post.

wow gold said...

Weekends to peopleig2tmean that they can have a two-day wowgold4europe good rest. For example, people gameusdcan go out to enjoy themselves or get meinwowgoldtogether with relatives and friends to talk with each storeingameother or watch interesting video tapes with the speebiewhole family.
Everyone spends agamegoldweekends in his ownmmoflyway. Within two days,some people can relax themselves by listening to music, reading novels,or watchingogeworld films. Others perhaps are more active by playing basketball,wimming ormmorpgvipdancing. Different people have different gamesavorrelaxations.
I often spend weekends withoggsalemy family or my friends. Sometimes my parents take me on a visit to their old friends. Sometimesgamersell I go to the library to study or borrow some books tommovirtexgain much knowledge. I also go to see various exhibition to broadenrpg tradermy vision. An excursion to seashore or mountain resorts is my favorite way of spending weekends. Weekends are always enjoyable for me.
igxe swagvaultoforu wowgold-usaignmax wowgoldlivebrogame thsaleGoldRockU

Adi said...

Find Internet Marketing resource hare Online Marketing Strategy Internet Marketing Tools Online Marketing Campaign Online Marketing Business Online Marketing System Online Business Online Home Business Online Business Tips Internet Marketing Online Online Marketing Affiliate Marketing Online Marketing Success Selling Online Free Online Marketing Online Marketing Tools Online Marketing Blog

Adi said...

Oes Tsetnoc one of the ways in which we can learn seo besides Mengembalikan Jati Diri Bangsa. By participating in the Oes Tsetnoc or Mengembalikan Jati Diri Bangsa we can improve our seo skills. To find more information about Oest Tsetnoc please visit my Oes Tsetnoc pages. And to find more information about Mengembalikan Jati Diri Bangsa please visit my Mengembalikan Jati Diri Bangsa pages. Thank you So much.
Oes Tsetnoc | Semangat Mengembalikan Jati Diri Bangsa

aiya said...

Office 2010is powerful!
Microsoft Office 2010is the best software in the world.
Microsoft wordis so great!
Office 2007makes life great!
Many people likeMicrosoft Office.
Microsoft Office 2007is welcomed by the whole world.
Office 2007 keyis available here.
Office 2007 downloadis on sale now!
Office 2007 Professionalbring me so much convenience.
Outlook 2010 make life wonderful!
Microsoft outlook is my love.
Microsoft outlook 2010 is convenient!
Windows 7 is convenient!

teramoney said...

Tera gold
wow gold

Tera gold
Tera Item
Tera account

buy eden gold
Runescape gold
buy Runescape gold

李小 said...

You may possiblyCheap Diablo 3 Gold consider mtss is a stage further and find the very first reference to springtime bean method change by itself in order that it does not have to undergo application_context.get_bean() every time. Not sure it might
Buy Runescape Goldenerate a difference, but it is a choice.

rscredits said...

What you share is really nice. You just give me the exact guidance on related issue, and now i could understand that in my way. rs gold , runescape gold

rsgoldorder said...

Again fantastic submit. Come on and blogging your website may well be more attractive. I always enjoy the interviews. I'm a editor of game site, you can visit and find diablo 3 gold, i like it very much.

AntoL-Nyo said...

HD kaliteli porno izle ve boşal.
Bayan porno izleme sitesi.
Bedava ve ücretsiz porno izle size gelsin.
Liseli kızların ve Türbanlı ateşli hatunların sikiş filmlerini izle.
Siyah karanlık odada porno yapan evli çift.
harika Duvar Kağıtları bunlar
tamamen ithal duvar kağıdı olanlar var

lisa Rweyer said...

i'm studying java , this article is very helpful to me, thank you

-----------------------
Rs Gold
Rs 3 Gold
Buy Rs Gold

dolinna said...

That is really cool. Thanks for finding it. Some really good ideas there, this is going to be a real time sink. I am a china tour lover,You can learn more: China travel packages | Asia tour packages | China city tour packages

shorry june said...

I love all of your missed connections so cheapest phone :) Keep up the great work!

ada3martin said...

So great! Due to the knowledge, I learn Günstige android-Handys ohne Vertrag online kaufenmore form this article!~ Thanks very much.

AntoL-Nyo said...

Ben istanbuldan selda 22 yaşında konfeksiyon içşisiyim Amatör Porno sizleri bekletmeden hemen hikayeme geçiyorum.. Biz 5 katlı bir binanın en üst katında yaşıyorduk ve bir öğlen paydosunda sevgilim beni Anal Sikiş aradı evdeydim çünkü evle iş yerim arasında 2 dakika bile yoktu.. Bende Asyalı Porno sevgilime benden telefon beklemesini söyledikten sonra evin durumuna baktım evde kardeşlerim ve annemin Esmer Porno birkaçtane arkadaşı vardı bu iş imkansızdı tekrardan düşündüm ve çatı katı aklıma geldi sevgilime telefon açıp çatıya çıkmasını ve Fantazi Porno beni beklemesini söyledikten sonra telefonu bir süre elime almadım anneme işe gidiyorum dedikten sonra Gay Porno hemen üst kata çatıya çıkıp sevgilimin
dudaklarına yumuldum az bir süremiz Götten Sikiş vardı ve çok istiyordum onu hemen önünde diz çöküp sikini çıkardım kocaman olmuştu bile... Özlemişti beni HD Porno bitanem başladım sikini yalamaya kafasını öpüyor onu çıldırtıyordum sevgilim saçlarımdan tutmuş ağzımı keyifle sikerken çatı katının kapısı açıldı toparlanamadan Lezbiyen Porno komşunun şişman oğlu efecan gelmişti ben dizlerimin üzerinde sevgilimin Liseli Porno siki ağzımda yakalanmıştım hemen bu halimizi gören komşu oğlu Sarışın Sikiş kaçarcasına gitti.. Sevgilim bir süre güldükten Türbanlı Porno sonra bu şişko neden kaçtı korktu herhalde onu sikicem sandı galiba dedikten sonra bir kahkaha daha attı ben sevgilimin Türk Porno sikine deli gibi saldırıyor yalıyor emiyordum boşalmasını istiyor Zenci Porno sütünü içmek istiyordum sevgilim ağzımı sike sike boşaldı hepsini yuttum bir damlasını ziyan Porno etmedim ve sevgilimle vedalaşıp ayrıldık... Ben her defasında sikiş yapmadan önce yazporno diye olan türkçe siteden Porno izle bölümüne girip seyrediyorum azdıktan sonra şahane sikiş ile gözleri kamaştırıyorum.