While at RubyMidwest I decided to explore Sinatra in more detail. I’ve spent a lot of time with Rails, and while I love it, there is something alluring about the simplicity of Sinatra (and, well… ooh shiny). Being a recovering Java developer (Hi, I’m R.J., and I haven’t developed in Java for 18 hours) I have a server that runs Java, and would like to be able to use Sinatra to build my fancy-awesome web-apps. On those lines, I want all of the shiny benefits of JRuby’s multi-threading awesome-ness, as opposed to just trying to use WEBrick, which does not a powerful server make. So here is a 2 minute tutorial (well, depending on the performance of your computer, and how fast you type) startup with Sinatra, JRuby, Bundler, and Glassfish
I’m cheating already by assuming you already have JRuby installed as your default Ruby installation. No? Go get it!
Next step is to get bundler:
1gem install bundler
Now we need to make a home for our application, and prep it for Bundler:
1mkdir testapp 2cd testapp 3edit Gemfile
Here I’m creating a new file in testapp called ‘Gemfile’ in your favorite editor. This is where we will sketch out our dependencies for Bundler to do all the hard work for us - here are the contents for this example:
1source :rubygems 2gem "sinatra" 3gem "glassfish"
Frankly, that’s it. We tell Bundler to look for gems in RubyGems core repo, and then we ask it to make sure we have Sinatra and Glassfish. Now we can create the program - create the file ‘hello.rb’, and use these contents:
1require "rubygems" 2require "bundler" 3Bundler.setup 4 5require "sinatra" 6 7get '/hi' do 8 "Hello World!" 9end
So what’s special for JRuby? Absolutely nothing. We do have special sauce for Bundler, (by calling Bundler.setup prior to the require for ‘sinatra’) but trust me - you’ll be happy you used it. You’ll also make @wycats happy.
And - that’s it! Now, if you were to start this file the standard (well, bundler-standard) way, we’ll see this:
1realjenius$ bundle exec hello.rb 2== Sinatra/1.0 has taken the stage on 4567 for development with backup from WEBrick 3[2010-07-17 11:24:46] INFO WEBrick 1.3.1 4[2010-07-17 11:24:46] INFO ruby 1.8.7 (2010-06-06) [java] 5[2010-07-17 11:24:46] INFO WEBrick::HTTPServer#start: pid=44490 port=4567
…and we can visit this URL: http://localhost:4567/hi. But, recall that our goal was to work with Glassfish, not WEBrick. All that has to change (and for folks who has done Glassfish/Rails before, this won’t be a surprise) is to run this startup instead
1realjenius$ bundle exec glassfish 2Log file /Users/realjenius/Projects/testapp/log/development.log does not exist. Creating a new one... 3Starting GlassFish server at: 0.0.0.0:3000 in development environment... 4Writing log messages to: /Users/realjenius/Projects/testapp/log/development.log. 5Press Ctrl+C to stop. 6 7Running sinatra
This time, we’ll visit this URL: http://localhost:3000/hi, and if all worked as desired, Sinatra will be crooning away. Boom goes the dynamite.