Paiza Engineering Blog

Engineering blog of browser-based web development environment PaizaCloud Cloud IDE ( https://paiza.cloud/ ), online compiler and editor Paiza.IO( https://paiza.IO/ )

Quick web development in browser using Ruby+Sinatra+PaizaCloud Cloud IDE!

f:id:paiza:20171219143149p:plain
(Japanese article is here)

f:id:paiza:20151217152725j:plainHi, I'm Tsuneo(@).

Everyone knows about Ruby on Rails, the Web application framework. sYes, Ruby on Rails is a major full-fledged MVC framework used in large-scale web applications.

At the same time, it is not very easy to use especially for beginners because there are many things to know in order to use Ruby on Rails.

Here comes Sinatra, yet another Ruby web application framework. Sinatra is a quite simple framework, so those who just learned Ruby can easily start writing.

When you start your first application, it is better to start with a small program, and then grow it step by step. With Sinatra, you can start with from 4 lines of code!

Well, it is another troublesome task to install and set up a Sinatra development environment and deploy it to the server. Because every PC has its own OS, application, and configuration, the setting up development environment often fails with errors.

Here comes PaizaCloud Cloud IDE, a browser-based web development environment. PaizaCloud Cloud IDE is quite flexible, and can be used not only for Ruby on Rails but also Sinatra. As both Sinatra and PaizaCloud Cloud IDE are simple and easy, it is the best combination for Ruby web development.

In this article, we'll actually develop a web service using Sinatra and PaizaCloud. We'll start with small program, and then create a web service that lookup a location from a host name, and shows it on the map.

By following the instructions, you'll create the application in about 10 minutes.

Getting started with PaizaCloud Cloud IDE

Let's start!

Here is the website of PaizaCloud Cloud IDE.

https://paiza.cloud/

Just sign up with email and click a link in the confirmation email. You can also sign up with GitHub or Google.

Create new server

Let's create a new server for the development workspace.

f:id:paiza:20171214154558p:plain

Click "new server" to open a dialog to set up the server. Just click "New Server" button in the dialog without any settings.

f:id:paiza:20171219143410p:plain

Just in 3 seconds, you'll get a browser-based development environment for Ruby on Rails.

Create application

Let's create a Sinatra application.

Create a Ruby file for Sinatra application. Here, we create a file "myapp.rb".

Click 'New file' button on the left side of the page.

f:id:paiza:20171219143513p:plain

Now, we see the dialog box to set filename. Set filename to "myapp.rb", and click 'Create' button.

f:id:paiza:20171219143628p:plain Now, let's create your first Sinatra code.

myapp.rb:

require 'sinatra'
get '/'
  'Hello ' + 'World'
end

f:id:paiza:20171218232517p:plain

After the coding, click 'Save' button or type "Ctrl-S" or "Command-S" shortcut to save to the file. When we see file finder on the left side of the page, we see a file "myapp.rb" that you just created.

Yes, it's a real web application with 4 lines of code.

Start Sinatra server

Then let's start the application.

To start the application, you need to run Ruby command. With PaizaCloud, you can use browser-based "Terminal" to run commands.

Click 'Terminal' button on the left side of the workspace.

f:id:paiza:20171214154805p:plain

Now, the Terminal started. Type commands like "ruby myapp.rb" and type enter key.

$ ruby myapp.rb

f:id:paiza:20171218232646p:plain

On the left side of workspace, you'll see a button with earth icon and "4567".

f:id:paiza:20171218232727p:plain

Sinatra server runs on port 4567. PaizaCloud Cloud IDE detects the port number(4567), and automatically adds the button to open a browser for the port.

Click the button, and you'll get Browser application(a browser application in the PaizaCloud). Now, you'll see web page with "Hello World".

f:id:paiza:20171219000404p:plain

Show HTML file

Next, instead of one message 'Hello World', let's create and show a HTML file.

Change "myapp.rb" to show HTML file as below. We use ERB template format to write Ruby code in the HTML file. We'll load "sinatra/reloader" to reload ruby code from the file after changing the code automatically.

myapp.rb:

require 'sinatra'
require 'sinatra/reloader'

get '/' do
    erb :index
end

Then, create a HTML(ERB) file.

On the left side of the workspace, right-click the home directory("/home/ubuntu"), and select "New Directory" to create a directory with name "views".

Then right-click the "views" directory, and select "New File", and create a file with filename "index.erb".

index.erb:

<h1>Host/IP Map</h1>

At the Terminal, type Ctrl-C to exit the running Sinatra application. Then, type "ruby myapp.rb" to restart Sinatra. As we load 'sinatra/reloader', we won't need to restart Sinatra from now.

Now, let's reload the Browser(in PaizaCloud). You'll see the HTML file created!

Install a package(gem)

We install a library to lookup locations from IP addresses. Ruby have a bunch of gem package, and we can add many features to the program. For now, we'll install a gem package called "maxminddb". We also download a database for the lookup.

Run following commands in the Terminal.

$ sudo gem install maxminddb
$ curl http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz -O
$ gunzip GeoLite2-City.mmdb.gz

f:id:paiza:20171218235045p:plain

At PaizaCloud, you can install whatever additional packages like this!

Show location, map

With maxminddb gem, let's lookup the location from the host's IP address. Also, show the map of the location using Google Maps.

Change the code("myapp.rb") like below. At "post" block, we can refer the hostname with field name "host" as "params['host']". Then, lookup IP address from the hostname, lookup location using the maxminddb, and set it to a instance variable "@geo". Instance variables like "@geo" can be referred from the ERB file.

Also, load "erubis" library to escape HTML automatically.

myapp.rb:

require 'sinatra'
require 'sinatra/reloader'
require 'maxminddb'
require 'erubis'
set :erb, :escape_html => true

db = MaxMindDB.new('./GeoLite2-City.mmdb')

get '/' do
    erb :index
end
post '/' do
    host = params['host']
    @ip = IPSocket::getaddress(host)
    @geo = db.lookup(@ip)
    erb :index
end

Change the ERB file. Add input tag to input a hostname or an IP address. When the form is submitted, show the contents of @geoip. <% if @geoip %> ... <% end %> means, the HTML inside the "if" block is shown only when the variable "@geoip" is available.

Also, show a map using iframe and Google Maps.

(We use Google Maps Embed API. Get your API key from here , and put it after "key=" of the URL.)

Also, let's add a CSS framework Milligram to make the HTML beautiful.

views/index.erb:

<html>
<head>
    <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Roboto:300,300italic,700,700italic">
    <link rel="stylesheet" href="//cdn.rawgit.com/necolas/normalize.css/master/normalize.css">
    <link rel="stylesheet" href="//cdn.rawgit.com/milligram/milligram/master/dist/milligram.min.css">
</head>
<body>
    <div class="container">
    <h1>IP&Host Map</h1>
    <form method="post">
        <input type="text" name="host" value="<%= params['host'] %>" placeholder="www.example.com or 127.0.0.1">
        <input type="submit">
    </form>

    <% if @geo %>
        <table>
            <tr>
                <td>IP</td>
                <td><%= @ip %></td>
            </tr>
            <tr>
                <td>Country</td>
                <td><%= @geo.country.name %></td>
            </tr>
            <tr>
                <td>Subdivision</td>
                <td><%= @geo.subdivisions[0].name %></td>
            </tr>
            <tr>
                <td>City</td>
                <td><%= @geo.city.name %></td>
            </tr>
        </table>
        <iframe src="https://www.google.com/maps/embed/v1/place?q=<%= @geo.location.latitude %>,<%= @geo.location.longitude %>&zoom=10&key=AIzaSyAAb1Nx1f7E6uNrEEiukZV5z9XX3TqkDNw" 
    width="600" height="300" allowfullscreen="allowfullscreen"></iframe>
        (<div>This product includes GeoLite2 data created by MaxMind, available from
<a href="http://www.maxmind.com">http://www.maxmind.com</a>.</div>)
    <% end %>
</body>    
</html>

That's it! You did it!

Let's open the web application in the browser(in PaizaCloud). You see the location and the map of the hostname you put!

(If you get an error, try to restart Sinatra. Exit "ruby myapp.rb" by "Ctrl-C", and run the command again.)

f:id:paiza:20171218235726p:plain

Summary

With PaizaCloud Cloud IDE, we created a Sinatra application just in your browser, without installing or setting up any development environments. The combination of Sinatra and PaizaCloud is one of the fastest and shortest way to create web application. Now, let's create your own Sinatra application!


With「PaizaCloud Cloud IDE」, you can flexibly and easily develop your web application or server application, and publish it, just in your browser. https://paiza.cloud