Jun 4, 2009

Glassfish, JRuby and Initialization Parameters

Sometimes in your Rails app you may want to pass some variable to your program, via an environment variable or something. With a regular Rails app, you can just do `export VAR_NAME=something` and it will detect it just fine. However if you're deploying in a container-based server like Glassfish or Tomcat, you'll have to pass the config values in a different way because it doesn't seem to pick up the enviroment variables.

You can do this with your warble config. If you haven't already done so, create your warble config file like this:
jruby -S warble config
This will create a file at config/warble.rb in your Rails app. Inside there you'll see all sorts of config settings for the JRuby environment.

What I wanted to do was output the SVN info on the site, so that when we were testing in the Glassfish environment we could see what revision we were working with. So I just had this little snippet of code:
`svn info` =~ /Revision: (\d+)/
revision = $1.to_i
Spit that out on the page somewhere and everyone can see what revision they're working with!

However the hard part is getting this into the WAR. What you have to do is pass it as a parameter in the warble config, like this:
config.webxml.svn_revision = revision
When warble runs, it will output this into the web.xml file within the WAR, which will get passed to your server.

To access this value from within the Rails app, you need something like this:
if defined?(JRUBY_VERSION)
revision = $servlet_context.getInitParameter("svn_revision")
end
If you're only ever running in JRuby then you don't need the if defined? junk.

The $servlet_context object is a Java object that represents the servlet context. I actually don't really know what that is, but a quick search of the docs gives a handy bit of info and the one you want is the getInitParameter method.

3 comments:

Anonymous said...

In Ruby (JRuby) you must change the Java method names in Camel Case to lowercase names separated by an underscore.

The above line should read:

$servlet_context.get_init_parameter("svn_revision")

Rob Britton said...

You don't have to change it (unless something has changed since the last time I used JRuby, which is definitely possible). The code above worked just fine for me.

Araxia said...

In the interests of clarity for anyone arriving here through the googles as I did, JRuby aliases all camelCase Java methods to corresponding snake_case names simply as syntactic sugar to allow for writing more idiomatic ruby code.

This is similar to the aliasing done for getters and setters, where object.value is equivalent to object.getValue.