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.

fileURI = URI.createURI('data/generated_library_std.ecore')
resource =
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

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 + "\t" + b.title+ "\t" + b.category.to_s + "\t" b.pages.to_s

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

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

Remark: This post was adapted to the new blog format in November 2016.