Create a gist now

Instantly share code, notes, and snippets.

JSON-JRuby with URLFetch on AppEngine

JSON-JRuby with URLFetch on AppEngine

Here is a Rack app that does a Twitter Search, and parses the result with json-jruby:

json-jruby.appspot.com

The “json-jruby” gem requires that you are running Java 1.6 locally. If this is a problem, you can instead use json_pure.

When using gems with Java extensions, appengine-tools drops the appropriate jars into WEB-INF/lib for you.

find .gems -name "*.jar"
.gems/bundler_gems/jruby/1.8/gems/json-jruby-1.2.0-universal-java-1.6/lib/json/ext/generator.jar
.gems/bundler_gems/jruby/1.8/gems/json-jruby-1.2.0-universal-java-1.6/lib/json/ext/parser.jar
require 'appengine-rack'
require 'appengine-apis/urlfetch'
require 'cgi'
require 'json'
AppEngine::Rack.configure_app(
:application => "hello",
:precompilation_enabled => true,
:version => "1")
def my_search(query)
url = "http://search.twitter.com/search.json?q=" + CGI::escape(query)
JSON.parse(AppEngine::URLFetch::HTTP.get(URI.parse(url)))
end
def my_html(query)
title = "JSON-JRuby and URLFetch on AppEngine"
cells = my_search(query)['results'].map { |e|
"<tr valign='top'><td><img src='#{e['profile_image_url']}' " +
"width='48'></td><td>#{e['text']}</td></tr>" }.join("\n")
html = <<HTML
<html><head><title>#{title}</title></head><body>
<h2>#{title}</h2><p>This is a Twitter Search for: #{query}</p>
<table style='width:500px; font-family:sans-serif; font-size:10pt;'><tbody>
#{cells}</tbody></table></body></html>
HTML
html
end
run lambda { |env| [200, {}, my_html('charles nutter') ] }
# Critical default settings:
disable_system_gems
disable_rubygems
bundle_path ".gems/bundler_gems"
# List gems to bundle here:
gem "appengine-rack"
gem "appengine-apis"
gem "json-jruby"
$ dev_appserver.rb .
=> Booting DevAppServer
=> Press Ctrl-C to shutdown server
=> Bundling gems
Calculating dependencies...
Updating source: http://gems.rubyforge.org
Caching: appengine-apis-0.0.12.gem
Caching: appengine-rack-0.0.6.gem
Downloading json-jruby-1.2.0-universal-java-1.6.gem
Downloading rack-1.1.0.gem
Installing rack (1.1.0)
Installing appengine-rack (0.0.6)
Installing appengine-apis (0.0.12)
Installing json-jruby (1.2.0)
Done.
=> Packaging gems
Installing generator.jar
Installing parser.jar
The server is running at http://localhost:8080/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment