Accessing EMF models with JRuby

January 27, 2008

JRuby provides access to Java packages, so it is possible to use packages created with the Eclipse Modeling Framework (EMF).

First we have to load the Java packages. The java packages have to be contained in the CLASSPATH.

include Java
include_class 'org.eclipse.emf.common.util.URI'
include_class 'org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl'
include_class 'org.eclipse.example.library.LibraryPackage'

Then we initialize the EMF package and load a file that contains the data of my little hardboiled library.

LibraryPackage.impl
fileURI = URI.createURI('data/generated_library_std.ecore')
resource = XMIResourceImpl.new(fileURI)
resource.load(nil)
library = resource.contents[0]

The following snippet prints out all the books.

library.books.each do |b|
    puts b.title+ "\t" + b.category.to_s + "\t" + b.pages.to_s
end

We can print out all the books with less than 240 pages with the following statement.

library.books.find_all { |b| b.pages < 240 }.each do |b|
    puts b.author.name + "\t" + b.title+ "\t" + b.category.to_s + "\t" b.pages.to_s
end

Or we can print out the titles of all the books of Raymond Chandler available.

puts library.books.find_all { |b|
    b.author.name == 'Raymond Chandler' }.collect { |b| b.title }.join(", ")