Mobile in Minutes with Sinatra

Sinatra is described as a DSL for quickly creating web applications in Ruby with minimal effort. Sinatra makes it extremely easy to host a web application and expose RESTful services. Here we’ll show how this allows you to get mobile applications up and running in minutes with Sinatra.

Quick Introduction to Sinatra

The following ruby file is a valid RESTful service with Sinatra:

require 'sinatra'
require 'json/pure'

get '/hello/:name.json' do
  content_type :json
  {
    "message" => "Hello #{params[:name]}!"
  }.to_json
end

Here we are telling Sinatra to respond to any GET requests to the URI pattern /hello/.json. The inserted name is passed to the method as a parameter through the params hash. We set the returned content_type to JSON to ensure correct handling from the client and our hash is converted to a JSON response using json_pure.

To run this example, save the above code snippet to file named hello.rb. Then install and run your new application with Sinatra:

$ gem install json_pure
$ gem install sinatra
ruby -rubygems hello.rb

Now navigate to the URL http://localhost:4567/Jacob (feel free to use your own name) and you will be presented with:

{"message":"Hello Jacob!"}

Now we can easily consume that service with a jQuery script and host the script with Sinatra:

<html>
  <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script>
      $.getJSON('/hello/Jacob.json', function(data) {
        alert(data.message);
      });
    </script>
  </head>
  <body>
  </body>
</html>

Here we use jQuery’s getJSON method to retrieve the JSON data from our service. The message from the JSON result is then alerted to the user.

To run the example, create a folder named public in the same directory where you created your hello.rb file. Inside that folder copy the above code snippet into a file named hello.html. Now navigate to the following page in your browser http://localhost:4567/hello.html. You will be alerted with the message “Hello Jacob!”

Creating a Mobile App with Sinatra

That was easy enough, but let’s see how we can apply this to a mobile setting. For this example, let’s create and consume a Sinatra service using jQuery Mobile.

Downloading and Running the Example

The example can be downloaded in its entirety here. To run the example, unzip the downloaded file to a known directory and execute the following commands:

$ cd /unzipped/folder/directory
$ gem install json_pure
$ gem install sinatra
$ ruby -rubygems cameras.rb

Now navigate to the following page in your browser http://localhost:4567/cameras.html. You will see the list of cameras for selection.

Exposing the RESTful Service

Let’s first create our RESTful service which will provide a top 10 list of popular DSLR cameras:

require 'sinatra'
require 'json/pure'

get '/cameras/top10.json' do
  content_type :json
  [
    {
      'id' => 1,
      'title' => 'Canon Rebel T3 DSLR',
      'description' => '...',
      'price' => '499.99
    },
    {
      'id' => 2,
      'title' => 'Canon Rebel EOS DSLR',
      'description' => '...',
      'price' => '349.99'
    }
    # ... ...
  ].to_json
end

In this case we are just constructing a hash that we then return back to the client in the same manner as our previous example. We could also retrieve the list of cameras from a database call, through an aggregation service, etc.

Setting up jQuery Mobile

Now we can consume the service with jQuery Mobile and host our mobile application with Sinatra. There will be two parts to our jQuery Mobile application, the HTML page which performs the setup for jQuery Mobile and a script which consumes our service. Let’s first take a look at the HTML page:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Top 10 Cameras</title>
  <link rel="stylesheet"
    href="//code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
  </script>
  <script src="cameras.js"></script>
  <script src="//code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js">
  </script>
</head>
<body id="page_body">
  <div id="cameraListPage" data-role="page">
    <div data-role="header">
      <h1>Camera List</h1>
    </div>
    <div data-role="content">
      <ul id="cameraList"></ul>
    </div>
  </div>
  <div id="cameraDetailPage" data-role="page">
    <div data-role="header">
      <h1>Camera Detail</h1>
    </div>
    <div id="cameraDetailContent" data-role="content">
    </div>
  </div>
</body>
</html>

The logic above is really just standard jQuery Mobile. We specify two pages, a #cameraListPage and a #cameraDetailPage. The #cameraListPage has an empty <ul> element which we intend to dynamically fill with cameras from our service. Similarly, the details page has no content which will be dynamically determined by selecting a camera from the list.

Rendering the Camera List

Now let’s have a look at the script that populates this logic. You can view the script in its entirety by downloading the example. The render method populates our <ul> by invoking our newly created camera service:

function render() {
  $.getJSON('/cameras/top10.json', function(data) {
    this.cameraData = data;
		
    var cameraListHtml = '';

    $.each(this.cameraData, function(i, camera) {
      cameraListHtml += '<li><a data-index="' + i + 
        '">' + camera.title + '</a></li>';
    });
		
    var $cameraList = $('#cameraList').append(cameraListHtml).listview();

    $cameraList.find('a').click(function() {
      displayCameraDetailPage(this, data);
    });
  });
}

Notice that the service data is retrieved in the same manner as our example above. The key difference is that we dynamically construct list items for each camera with a link that holds the index of the camera it refers to. The list items are then appended to the #cameraList which is rendered as a jQuery Mobile listview.

Showing the Camera Details

The final step is displaying the camera details. The displayCameraDetailPage method is bound to each camera link that was generated. The method is passed the <a> element and the camera data we retrieved from the service.

function displayCameraDetailPage(element, cameraData) {
  var camera = cameraData[$(element).data('index')];

  var detailsHtml = 
    '<div data-role="content"><h2>' + camera.title + '</h2>' + 
    '<p><strong>Price:</strong> ' + camera.price + '</p>' +
    '<p>' + camera.description + '</p>' +
    '</div></div>';
	
  $('#cameraDetailContent').html(detailsHtml);

  $.mobile.changePage('#cameraDetailPage');
}

Here we make use of the jQuery data method to retrieve the index of the camera that was selected. A markup representation of the details of the camera is generated and the #cameraDetailPage content is updated. Once the update is complete, the jQuery Mobile changePage method is used to show the #cameraDetailPage.

Sinatra makes it easy to develop web applications quickly. Try it and your sure to get your next mobile application up and running in minutes.

Upgrading a Seam 2 app to JBoss 7

I recently went through the process of upgrading a Seam 2.X application to JBoss 7.1.1. While Marek Novotny’s tutorial will lead you down the right path, there was one issue that led me down a rabbit hole.

Initially, the intention was to use Hibernate 3 as a JBoss module allowing it to be shared among applications. This deviates from the tutorial, but simplifies the library requirements if you are deploying several Seam 2 applications to the same server. Unfortunately, this issue cropped up:

14:54:13,042 WARN  [org.jboss.modules] 
  (MSC service thread 1-4) Failed to define class 
  org.jboss.as.jpa.hibernate3.infinispan.InfinispanRegionFactory 
  in Module "deployment.jboss-seam-booking.ear:main" from Service Module 
  Loader: java.lang.LinkageError: Failed to link org/jboss/as/jpa/hibernate3/
  infinispan/InfinispanRegionFactory (Module "deployment.jboss-seam-
  booking.ear:main" from Service Module Loader)
...
Caused by: java.lang.NoClassDefFoundError: 
  org/hibernate/cache/infinispan/InfinispanRegionFactory
...
Caused by: java.lang.ClassNotFoundException: 
  org.hibernate.cache.infinispan.InfinispanRegionFactory from 
  [Module "deployment.jboss-seam-booking.ear:main" from Service Module Loader]

Apparently this problem will be resolved in JBoss 7.1.2, but in order to get something working now an alternative approach was necessary.

The next step was to attempt to bundle the Hibernate 3 jars within the application as discussed in the tutorial. This worked fine except that JBoss still attempted to manage Hibernate 3 as a JPA provider. This produced the same exception shown above.

After researching the issue, the following setting was discovered. This setting is specified for each persistence unit in persistence.xml:

<properties>
   <property name="jboss.as.jpa.managed" value="false"/>
</properties>

Success! This setting stops the JBoss container from managing Hibernate 3 as a JPA provider. Once this setting was changed, the application deployed successfully.

By |JBoss Seam|Comments Off on Upgrading a Seam 2 app to JBoss 7

Re-imagining the App Store in the Cloud

The app formerly known as PhoneGap (now Apache Cordova) started out with a very telling name. PhoneGap/Cordova bridges the gap between a native application’s and a browser’s access to device APIs, thereby allowing you to develop apps in pure HTML5, CSS3, and JavaScript. In addition, you can wrap up and deploy your web-standards-based application to an app store.

But a native OS could provide the same API through the browser. The major drawback to this approach is the loss of revenue generated by the app store through app purchases and in-app purchases. This gives little incentive for OS manufacturers to implement these APIs through the browser. But let’s re-imagine the app store in the cloud for a moment and see how browser support for native APIs could enable this.

Mobile Devices as a Portal

A recent article on Technorati described Google’s new hardware offering which essentially provides a “portal into Google-land.” Chrome essentially becomes the OS for the device and Google Drive becomes the hard-drive. Expanding this idea into the mobile realm is not difficult to imagine, but what value does this provide other than giving us a common place to store documents and photos?

Right now the focus of the cloud in terms of consumers has seemed to revolve around storage. How can I get all of my “stuff” in one place where I can access it from anywhere? Think DropBox, Google Drive, etc. This is an interesting problem, but only the beginning. The next step is taking our Apps and making them accessible from anywhere. After buying a new App for my phone, it would be great if I had immediate access to this same App from my other devices, my tablet, my laptop, etc. and vice versa without the need to download anything on those devices.

App Store in the Cloud

Chrome recently released the ability to login, making your tabs and bookmarks accessible across all devices that are running Chrome. This is a novel concept and could be further applied to the App Store. The starting point in your browser could be a layout of all of the Apps that you have purchased and would look very similar to the native OS representation of your App icons. In addition, one of those Apps could guide you to the App Store which allows you to purchase these Apps. Each App then runs directly in your browser and stores all its data on an external server.

This may appear to have little value initially, but now I could login to my tablet and immediately have access to the same App that I just purchased through its browser. All of my data would be accessible and there is no requirement to find and download anything further. By implementing Apps using web standards (HTML5, CSS3, and JavaScript), the adjustment between devices could all be handled through styling differences. This allows the OS manufacturers to continue to reap revenue from App store purchases, while giving the consumer the advantage of ubiquitous access to their Apps. You could even imagine a pricing model that differs based on which devices you want to enable access from.

The Future is Here… Almost

Firefox OS takes exactly this approach. From the introduction:

The idea is essentially to have all user-accessible software running on the phone be a Web app that uses advanced HTML5 techniques and device APIs to access the phone’s hardware directly via JavaScript. For Web developers, the most important part to understand is that the entire user interface is a Web app, one that is capable of displaying and launching other Web apps. Any modifications you make to the user interface and any applications you create to run on Firefox OS are Web pages, albeit with enhanced access to the mobile device’s hardware and services.

To publish a web application as a Firefox OS App, you simply have to add an app manifest, “a JSON file that describes your app, including its name, its icons, and a human-readable description.” The Marketplace then uses the information provided by the manifest to publish your web application to Firefox OS users.

Firefox OS will likely spurn competition between the OS manufacturers and it appears that Google is already making inroads into the approach with their recent releases. At the moment, the following issues remain although several will likely be solved in the next few years:

  • Native APIs – the Android and iOS browsers just don’t have access to them… yet. Apache Cordova has been a well-recognized stop-gap approach, but as browsers continue to adapt, will no longer be necessary in the future.
  • Performance – Facebook CEO Mark Zuckerberg recently discussed the issues with browser performance on mobile devices after choosing HTML5 as their strategic approach. This will only improve as time goes on and devices become more capable.
  • Connectivity – ubiquitous connectivity just doesn’t exist yet. In the basement of the parking garage, on a remote island… still having access to certain applications is beneficial in these scenarios.
  • Games – as with desktop computing, games require an extensive amount of native API access and have performance requirements that put general Apps to shame. Unless there are breakthroughs in SVG support that make gaming a snap in the browser, games will likely remain native.

Being a believer in web standards and seeing the exciting possibilities of HTML5, Firefox OS truly presents a breath of fresh air. Let’s hope that the other OS manufacturers take notice.

Stimulating Creativity for an Agile Team

I’ve always noticed that my creativity level drops when my routine becomes predictable. Suddenly my mind moves into cruise control. I find it difficult to come up with creative ideas and innovative approaches. I write fewer blog postings, my software solutions are more brute force, and I’m less likely to come up with fun new games to entertain my kids.

There is some science behind this as discussed in the Fast Company article, 7 Ways to Stimulate Your Capacity for Creativity. Essentially the article discusses how context violations spur creativity.

The idea is that our minds need exposure to a variety of contexts to keep us innovative:

Your most creative insights are almost always the result of taking an idea that works in one domain and applying it to another. Every “new” idea you have, personally, is based on some combination of previous concepts in your own mind, even if you combined these concepts subconsciously.

Studies in neurology have also shown that forcing our mind to think through new scenarios and differing contexts creates new neural pathways.

While the article focuses on stimulating creativity for an individual, a similar list of ideas can be applied to Agile teams. Try these ideas to boost creativity within your team:

  • Change the team environment. Have meetings in unusual locations and try switching seating arrangements regularly. How’s the weather? Have a meeting outside if the corporate campus is suitable.
  • Brainstorm different ways to use a common tool (grep, ls, ftp, whatever your team uses regularly). This may not only stimulate creativity, but can lead to new useful ways that the team uses tools you’re already familiar with.
  • Spend 30 minutes a day for two or three weeks learning a new programming language. Make it a story to be addressed during a sprint and set aside time. You may even decide the language is useful for product development.
  • Have the team talk with one new product user every week. This forces developers to socialize and it has the advantage of creating opportunities for learning. Each product user likely has a different take on the system and what they find useful.
  • Play Agile games. Ever been to TastyCupcakes.org? Other than the creepy clown picture on the front page (think It, Stephen King), this is a great site for finding games that allow a team to learn more about Agile while spurring innovation.
  • Take on a story for innovation time. It works for Google, could it work for your team? Try bringing in a story during your next sprint focusing time on innovation (this should be only a few story points). Make sure you set acceptance criteria so the team can demonstrate their effort.
  • Try a daily 10 minute break for exercise. One of my clients is a wellness company and they take 10 minutes a day to leave the cubicle farm to get some brief exercise. Walk the stairs, jog in place, do some situps, change it up daily. Not only will it change the daily routine, it promotes good health!

Do you have ideas of your own? Leave them in the comments.

By |Agile|Comments Off on Stimulating Creativity for an Agile Team