Chapter 4. Creating an Application from Scratch

The AppFog console is a very useful tool, but you can also create applications completely from the command line. In this chapter, we will create a simple application directly from the command line and publish it as a new application to AppFog.

Creating an application

We could use the application we created and downloaded in Chapter 2, Using the Command Line Tool, however we are going to create a very new application. This application is also going to be a Sinatra application that displays some basic date and time information.

First, navigate to a new directory that will be used to contain the code. Everything in this directory will be uploaded to AppFog when we create the new application.

$ mkdir insideaf4
$ cd insideaf4

Now, create a new file called insideaf4.rb. The contents of the file should look like the following:

require 'sinatra'

get '/' do
  erb :index
end

As we saw in the previous chapter, this tells Sinatra to listen for requests to the base URL of / and then render the index page that we will create next.

If you are using Ruby 1.8.7, you may need to add the following line at the top, as described in Chapter 2, Using the Command Line Tool:

require 'rubygems'

Next, create a new directory called views under the insideaf4 directory:

$ mkdir views
$ cd views

Now we are going to create a new file under the views directory called index.erb. This file will be the one that displays the date and time information for our example.

The following are the contents of the index.erb file:

<html><head>
  <title>Current Time</title>
</head><body>
  <% time = Time.new %>
  <h1>Current Time</h1>
  <table border="1" cellpadding="5">
    <tr>
      <td>Name</td>
      <td>Value</td>
    </tr>
    <tr>
      <td>Date (M/D/Y)</td>
      <td<%= time.strftime('%m/%d/%Y') %></td>
    </tr>
    <tr>
      <td>Time</td>
      <td><%= time.strftime('%I:%M %p') %></td>
    </tr>
    <tr>
       <td>Month</td>
       <td><%= time.strftime('%B') %></td>
    </tr>
    <tr>
      <td>Day</td>
      <td><%= time.strftime('%A') %></td>
    </tr>
  </table>
</body></html>

This file will create a table that shows a number of different ways to format the date and time. Embeded in the HTML code are Ruby snippets that look like <%= %>. Inside of these snippets we use Ruby's strftime method to display the current date and time in a number of different string formats. At the beginning of the file, we create a new instance of a Time object which is automatically set to the current time. Then we use the strftime method to display different values in the table.

For more information on using Ruby dates, please see the documentation available at http://www.ruby-doc.org/core-2.0.0/Time.html.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.29.71