Skip to content

Instantly share code, notes, and snippets.

@nicksieger
Created November 11, 2008 17:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicksieger/23909 to your computer and use it in GitHub Desktop.
Save nicksieger/23909 to your computer and use it in GitHub Desktop.
package jruby.ext;
import java.util.Arrays;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.jruby.embed.ScriptingContainer;
/**
* Launch a Ruby script at web application startup. To wire up this
* listener, add
* <listener-class>jruby.ext.StartupScriptLauncher</listener-class> to your
* application's web.xml file.
*
* @author nicksieger
*/
public class StartupScriptLauncher implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
ServletContext servletContext = event.getServletContext();
ScriptingContainer container = new ScriptingContainer();
try {
container.setLoadPaths(Arrays.asList(new String[] {
// set up any $LOAD_PATH items here
servletContext.getRealPath("/WEB-INF"),
servletContext.getRealPath("/WEB-INF/lib")
}));
// setup any global variables
container.put("$servlet_context", servletContext);
// require e.g., WEB-INF/config/startup.rb
container.runScriptlet("require 'config/startup'");
} catch (Exception ex) {
ex.printStackTrace();
servletContext.log(ex.getMessage());
} finally {
container.terminate();
}
}
public void contextDestroyed(ServletContextEvent event) {
}
}
@cmw
Copy link

cmw commented Sep 22, 2011

I've successfully added the class to my war file, but the startup script doesn't seem to be run or output an error.

@cmw
Copy link

cmw commented Sep 23, 2011

Also, to compile the code I had to put

Ruby runtime = null;

into line 21, to avoid errors.

@nicksieger
Copy link
Author

nicksieger commented Sep 23, 2011 via email

@cmw
Copy link

cmw commented Sep 23, 2011

The wrong directory structure was the first problem, I found that out by looking at a similar java class and its documentation. Now tomcat does not error out anymore but seems to actually find the launcher. It just doesn't seem to launch the corresponding script.

@nicksieger
Copy link
Author

Hmm. Can you try this updated version that uses org.jruby.embed instead? You can also figure out what scripts are getting loaded by adding

System.setProperty("jruby.debug.loadService", "true");

at the beginning of the contextInitialized method.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment