Showing posts with label locate. Show all posts
Showing posts with label locate. Show all posts

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.