September 14, 2007

Waffle: How to access your Java components from your Ruby Actions.

In my last post I gave an overview of how you can easily integrate JRuby with Waffle. Now we will examine Ruby based controller in a bit more depth. Lets assume we have the following Waffle Registrar for our application:
public class MyRegistrar extends AbstractRubyAwareRegistrar {

public MyRegistrar(Registrar delegate) {
super(delegate);
}

@Override
public void application() {
register("the_dao", PersonDAOImpl.class);

registerRubyScript("person", "PersonController");
}
}

A DAO, PersonDAOImpl, is registered under the name "the_dao" and we have one Ruby based controller available. Now its probably safe to assume that this Ruby PersonController will need access to the DAO. Gaining access to this DAO from the controller is easy in Waffle, just call the locate method:
class PersonController

def index
@person_dao = locate(example.PersonDAO)

@people = @person_dao.findAll
render 'person.rhtml'
end

end

Notice that we were able to retrieve the DAO by its interface. Additionally, since this DAO was registered with a key you can use a convention to retrieve the component. The convention is "locate_<component key>", here is the same controller using the locate_ convention:
class PersonController

def index
@person_dao = locate_the_dao

@people = @person_dao.findAll
render 'person.rhtml'
end

end

As you can see this makes writing Ruby based Controllers/Actions with Waffle really easy. In my next post I'll detail how to access request parameter and context attributes with ease.

4 comments:

Dave Hoover said...

I think it would help to see the PersonDAOImpl and PersonDAO implementations, which might clarify why you have to say "example.PersonDAO" rather than just "PersonDAO".

Anonymous said...

Hi Mike, good post! Would be useful to link to the site because at the moment it looks like there is no activity around the framework. Also you did not get back to me regarding my patch (handling multi implementations in registrat) regards, peter

Michael Ward said...

Dave - the "example." prefixing PersonDAO was the package name PersonDAO exists in. I probably should of shown the import statement in the examples.

Michael Ward said...

Peter - I plan on adding documentation for JRuby support on the Waffle web site, hopefully soon. The great thing about blogging on this is it give me a quick way to get the info out and receive feedback.

Did you submit your patch through the waffle mailing lists, or JIRA? If not could you do that?

Thanks for your comments.