Building Mobile Web Applications With Kendo UI And Engine Yard
Note: Burke Holland, a developer at Telerik originally published this article about building mobile web apps on his own site, and with his approval, we’re republishing it here.
Kendo UI is an HTML5 UI framework that contains everything that you need to create rich, next generation HTML5 apps. Built on jQuery, its familiar syntax and pixel perfect themes have made it the go-to choice for building lights out awesome cross-browser compatible applications. It’s fairly well known for it’s robust Web Widgets, as well it’s Data Vizualization package which delivers interactive animated charts built on SVG. But did you know that Kendo UI is about to launch a mobile toolkit as well?
Kendo UI Mobile is a brand new framework for building mobile applications. Kendo UI Mobile does something you may not have seen before: It adapts to the native look and feel of the device that loads it (iOS and Android currently supported). You can get a native iPhone or Android application experience without touching a line of native code. In this example, we’ll build a very simple Ruby On Rails application using Kendo UI Mobile and then deploy it to Engine Yard for superb EC2 cloud hosting.
Estimated Time To Complete: 20 Minutes
I am going to create a sample application called “Conference Tracker”. This simple mobile app will allow conference goers to stay connected with the latest news as well as viewing the schedule of sessions. Let’s take a look at the finished application first:
That’s the exact same application running on the web. Looks pretty native doesn’t it? Let’s take a look at how we can do this with Rails, Kendo UI and Engine Yard.
Download The Bits
I’m going to assume in this article that you have a familiarity with Ruby On Rails. There is a great guide on how to get up and running with Rails here. It’s really very simple and I encourage you to give it a try if you aren’t familiar with Rails. I’m going to be working with TextMate on a Mac, but Rails will work just fine on Windows as well.
The first thing you will need to do is to download the Kendo UI Mobile Beta.
Unzip those file to a location on your local drive. It doesn’t really matter where you put files, just don’t forget where they are!
Now lets create our Rails application.
> rails new ConferenceTracker
> cd ConferenceTracker
That was easy. The first line creates the application and all needed files. The second line just moves us into that directory so we can work with our project. Go ahead and fire up the server to make sure things are working.
> rails server
If everything went as planned we’ll see the “You’re Riding Ruby On Rails!” page.
If you don’t see this page, make sure you changed directories into your newly created rails project. That is the most common error. Now lets remove this wonderful welcome page. You may need to open another command line / terminal window in the ConferenceTracker directory if you don’t want to stop the server. If you want to stop the server, hit ctrl+c. Back to removing the welcome page…
> rm public/index.html
(## Gain Some Control Rails is the original MVC goodness, so our development concept here is Model (the data), View (our html pages) and Controller (a Ruby class that routes our requests and performs actions). We no longer have a public.html file so we have nothing to show. We’ll go ahead and create a home controller which will return a view that we’ll use as our index. Rails has a generator that we can use to create a controller. This controller will be empty.
> rails generate controller Home index
This generates a home_controller in the app/controllers folder. It also creates an index.html.erb file in the app/views/home folder. This is the file we want returned when people hit the root of the site.
The home controller index method will return the index html file in the app/views/home folder. That code alone isn’t quite enough to do it though. We also need to define a route that tells our application, “when you load up, go to this controller method”. Open up the routes.rb file which is located in the config folder. In that file, scroll down to the bottom and add the following line…
# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
root :to => "home#index"
Now load up the application (rails server
) or if you have the server running already, just hit refresh. You will see the contents of the new index.html.erb file returned by the controller.
Add In Some Kendo UI
Remember where you unzipped those Kendo UI Mobile beta files? You forgot already? It’s probably on your desktop with everything else you unzip. Copy the files out of the js directory to the app/assets/javascripts directory. Specifically speaking, this should be jquery.min.js and kendo.mobile.min.js. Additionally, copy the kendo.mobile.all.min.css file and the images folder to the app/assets/stylesheets directory. Now jump over to the index.html.erb file in the__app/views/home__ directory. In that file is where we will be building our application.
First let’s take a look at the markup and then we’ll have a look at how to turn it into a Kendo UI Mobile Application.
<div data-role="layout" data-id="app">
<header data-role="header">
<div data-role="navbar">Conference Tracker
</header>
<footer data-role="footer">
<div data-role="tabstrip">
<a href="#info" data-icon="info">Info</a>
<a href="#schedule" data-icon="recents">Schedule</a>
</footer>
<div data-role="view" data-init="getInfo" data-layout="app" data-title="info" id="info">
<div id="news">
<div data-role="view" data-layout="app" data-init="getSessions" data-title="schedule" id="schedule">
<ul id="sessions"></ul>
That’s not a whole lot of markup, so let’s talk about what we have.
The first div
defines the layout or masterpage of the application. This is where we define the header
and footer
. The two divs below this one will be loaded into the layout. Everything in Kendo UI Mobile is powered by data attributes. The data-role is how Kendo UI will know that the header is in fact a header. Inside of that is a NavBar component. In the footer is a TabStrip. All of these widgets will be initialized once we kendo-ize this project.
Let’s go ahead and add the magic. Add the following block of JavaScript below the HTML in the index.html.erb file.
<script>
var app = new kendo.mobile.Application($(document).body);
</script>
That’s it! If we preview the app now, it looks like an iOS Application – or Android if you are on Android.
Rails Is At Your Service
Let’s use Rails to create some data for the project.
We’ll use the Rails generator to generate two different endpoints for our application. One will return generic info for the info tab, and the second will return the conference schedule. Before we can do that though, we need to create our database. By default, Rails uses SQLite3 – which is a popular file-based database. If you look in the gemfile, you will see that “sqlite3” is named as the database gem. This is totally fine for both us and Engine Yard. Engine Yard has no problem with SQLite3, although it’s recommended that you go with a MySQL or PostgreSQL database. Engine Yard will create one of these for you when you deploy your application. Editor’s note: The Engine Yard platform will generate a SQLite-compatible database.yml to avoid deployment failures but SQLite remains unsupported.
For now, leave it at SQLite3. Let’s create the database.
> rake db:create
That was easy. Now let’s create the Info table. While we’re at it, we’re going to create all the interface elements for you to enter data into this table as well. Rails has a scaffold method which will do all this for you.
> rails generate scaffold Info content:text
The Info table is pretty simple. It only has a content field. But Rails is smart. It’s also going to create an id field, as well as created_date and modified_date fields which it will keep up with for you. Loving Rails yet? Let’s also scaffold out the Sessions table. Table’s should be named in the singular. Rails is aware of pluralization and will take care of that for us.
> rails generate scaffold Session time:datetime speaker:string title:string
Now let’s push these changes to the database so the tables get created.
> rake db:migrate
Done! Fire up a browser and add some data to your application. You can go to http://localhost:3000/infos to add new info. You will have create, update and delete pages already created. The same goes for Sessions. –http://localhost:3000/sessions. See how Rails automatically pluralizes the data structures?
Put Some Data In Those Views
Now that we have some data, let’s put it in the views on the Kendo UI Mobile application. Views have an init event that we can define in the data-init attribute. This is the function that will be called when the view is initialized. There is also a__show__ event that is fired every time the view is shown. If you notice in the HTML above, these functions have already been defined. We just need to implement them. Add the following methods to your script block and I’ll explain what they do.
var getInfo = function() {
// read from the remote data source
$.get("infos.json", function(data) {
$.each(data, function() {
$("#news").append("" + this.content + "");
});
});
}
var getSessions = function() {
$("#sessions").kendoMobileListView({
dataSource: kendo.data.DataSource.create({
transport: {
read: "sessions.json"
},
group: "day",
sort: { field: "time", dir: "asc" }
}),
template: $("#sessionsTemplate").html()
});
}
getInfo
This function is pretty simple. It’s using jQuery to call out to the infos.json endpoint that returns the data from the Info__table in our database. It then iterates over each item and adds it to the view in a __p tag. It also applies a class with some minor styling for visual appeal.
getSessions
This one is a bit more interesting. It’s selecting the sessions div and turning it into a ListView widget by calling kendoMobileListView(). Inside this widget definition, it defines an instance of a Kendo UI DataSource – which is a data layer abstraction that provides rich client-side sorting, grouping, paging and filtering as well as handling AJAX requests for you. I have also defined a Kendo UI Template for it to use for each row in the list. The template needs to be added to the markup, just above our <script> block.
<script type="text/x-kendo-template" id="sessionsTemplate">
<div class="left">
<div class='time'>${ formatted_time }
<div class='speaker'>${ speaker }
${ title }
</script>
Kendo UI Templates are a powerful and integral part of development with Kendo UI. Refer to the documentation for more info on the templates.
There is one more thing that we need to do before we can use this application. The time that Rails is going to send back is going to be, well, not formatted correctly for our needs. We need to do that. We also need to return a day field that we did not specify in the scaffolding of the Session model.
Open up app/models/session.rb. In that file, we are going to add two new fields to be returned. The first one is a field called formatted_time, and the second is called day. Ruby can format strings using the strftime method. We can format the time and also return a day field that we can group by. Add the following lines to the file.
class Session < ActiveRecord::Base
def formatted_time
time.strftime("%I:%M %p")
end
def day
time.strftime("%A")
end
end
We also need to include these in the return from the controller. Open up app/controllers/sessions_controller.rb, and inside the index method (the very first method), change the line that starts with format.json to the following… format.json { render :json => @sessions.to_json(:methods => [:formatted_time, :day]) }
Now we have all the data we need, and in the right format. Fire up the app and have a look? I’ve added a few sessions from the jQuery 2010 Conference as sample data. Additionally, I added some announcements for our conference goers.
Now you are probably previewing through a browser at the moment. I am using the iOS Emulator and Safari so that my app looks like it will look when I browse to it on my phone.
Wait! We Didn’t Include Any Scripts or CSS Files!
Actually, Rails is doing that for you. It’s taking all of the files you dropped into those directories, minifying them and then putting them into the page.
All Aboard For Deployment
Lets push this bad boy up to Engine Yard and see how easy it is to deploy it to the cloud. Engine Yard offers you a free 500 hours of hosting to get you up and running in no time flat. Head over to https://engineyard.com and select the __Ruby__hosting option. Optionally, click here to go directly to the Rails signup. Once you have signed up for a new account, you will receive a verification email. Follow the directions in that email to activate your account.
Now that you are logged in, select Engine Yard Cloud.
Engine Yard pulls your code off of GitHub. We need to push it to a repository there and then enter that repository URL here. Setting up GitHub is very easy and you can find in depth instructions here.
Enter your GitHub repo URL, a name and leave the default Rails 3 selection. Click Create Application.
At this point, Engine Yard will begin creating your application instance. The next step is to migrate your db and deploy the application. You need to wait until Engine Yard is done setting up your environment before you deploy or it will tell you that your instance is not ready when you click the deploy button. Editor’s note: The Engine Yard platform automatically deploys your application—with migrations—upon first boot, when the instance is ready.
You’re Done!
When Engine Yard is done setting up and deploying your application, you can click on the link to visit your app on the web. You now have a mobile application running on the web that has a completely native look at feel. Try it on different devices and watch as it adapts to the platform to make it seem like you are on the device, not on the web.
Kendo UI also has full featured Web UI Widgets, Data Vizualization, and a wealth of framework goodness. It’s everything you need for rich interactive HTML5 websites that you can be sure will work across all major browsers. Be sure todownload Kendo UI today and hit up our forums or UserVoice site with any feedback or questions.
Share your thoughts with @engineyard on Twitter