Sunday, December 4, 2011

Installing clipgrab (Youtube downloader) on Ubuntu (11.04)

Installed clipgrab, a Youtube video downloader.

1. Reference(s)
Youtube video: http://www.youtube.com/watch?v=HTA7smqOBUY

2. Add a PPA repository.
$ sudo add-apt-repository ppa:clipgrab-team/ppa

3. Install.
$ sudo apt-get update
$ sudo apt-get install clipgrab

Saturday, December 3, 2011

Installing rush on Ubuntu (11.04)

I've installed rush (a Unix shell replacement based on Ruby)

1. Resource(s)
rush home page: http://rush.heroku.com/

2. Installation
$ gem list rush --remote
*** REMOTE GEMS ***
rush (0.6.7)
rushcheck (0.8)
rushiro (1.0.0)

$ sudo gem install rush
Successfully installed fattr-2.2.0
Successfully installed session-3.1.0
Successfully installed rush-0.6.7
3 gems installed
Installing ri documentation for fattr-2.2.0...
Installing ri documentation for session-3.1.0...
Installing ri documentation for rush-0.6.7...
Installing RDoc documentation for fattr-2.2.0...
Installing RDoc documentation for session-3.1.0...
Installing RDoc documentation for rush-0.6.7...

3. Launching rush
$ rush
rush>

4. Testing
rush> root.ls      # 'root' is one of predefined variables, the other being 'home'
////
  bin/
  boot/
  cdrom/
  dev/
  etc/
  home/
  lib/
...
rush> htmldir = home['public_html/']     # get sub directory
=> localhost:/home/socrateos/public_html/
rush> htmldir.ls                         # ls command
/home/socrateos/public_html/
  apps/
  domain1.com/
  domain2.com/
  domain3.com/
rush> htmldir['apps/dbmanager/'].ls      # sub directory of sub directory...
/home/socrateos/public_html/apps/dbmanager/  
  controller/
  layout/
  model/
  public/
  spec/
  view/
  app.rb
  config.ru
  start.rb
rush> file=htmldir['apps/dbmanager/app.rb']  # file object
=> localhost:/home/socrateos/public_html/apps/dbmanager/app.rb
rush> file.class                             # typical ruby command
=> Rush::File
rush> file.name                              # file name
app.rb
rush> file.path                              # display file path 
/home/socrateos/public_html/apps/dbmanager
rush> file.size                              # get file size
=> 385
rush> file.read                              # displays file content (lines 41-54)
# This file contains your application, it requires dependencies and necessary parts of 
# the application.
#
# It will be required from either `config.ru` or `start.rb`
require 'rubygems'
require 'ramaze'

# Make sure that Ramaze knows where you are
Ramaze.options.roots = [__DIR__]

# Initialize controllers and models
require __DIR__('model/init')
require __DIR__('controller/init')

rush> file.search('__DIR__')                  # search file content
Ramaze.options.roots = [__DIR__]
require __DIR__('model/init')
require __DIR__('controller/init')
=> 3 x String

rush> exit                                    # exit from rush shell, and back to bash shell

Sunday, November 6, 2011

Learning Ramaze (4) - Updating Body Contents

I am learning Ramaze, a small Ruby web framework. I am building an application that will be used for PostgreSQL database management.

My application has four main pages: Home, Data, Design and System. I have finished learning how to navigate between these pages. Now I would like to learn how to update body section of contents of each pages. I do not want to load a whole page when changes are limited to the body section of the page.

In this post, I would like to modify my Home page, which is the simplest of all. The Home page basically explains what this application does (PostgreSQL database management), and what features it has (Data, Design, System). It can be static as is now, but I would like to add some interactive elements. I would like to add a link (or button) for each section so that when it is clicked, it will expand the description, showing more information in detail. When it is clicked again, it will shrink to display a short, original description.

1. Resource(s)
Ramaze: http://www.ramaze.net/
AJAX Tutorial: http://www.w3schools.com/ajax/default.asp
My first post: Learning Ramaze (1)
My second post: Learning Ramaze (2)
My third post: Learning Ramaze (3)

2. How to Update Contents without Loading Whole Page
An event such as mouse click triggers a process of content updates. Browser builds a request message and sends it to the server. The server processes the request and builds a response message, optionally accessing database or file system. Then it sends the response message back to the browser. The browser process the response and updates the content accordingly.






























3. Identifying Target (Part(s) of Contents) to Update

In my Home page, it is the "Features" section where I want to update its contents upon an event of user request. For example, when user clicks on "Design" item of the feature list, I want to display a longer description of that feature. So I enclose each item with
<div id="..."></div>tag and provide with unique IDs.
...
<ul>
  <li>
    <div id="design">Create and Design Databases.</div>
  </li>
  <li>
    <div id="data">View/Add/Edit/Delete Database Records.</div>
  </li>
  <li>
    <div id="report">Generate Reports.</div>
  </li>
  <li>
    <div id="system">Configure System.</div>
  </li>
</ul>


4. Planting an Event Handler that Triggers a Chain of Actions

An event such as mouse click starts a chain of actions that in the end update the specified part(s) of page contents. A javascript is used to handle this event and send its request to the server. In my Home page, I append "(read more...)" as an anchor at the end of each list item, and when it is clicked, it calls a javascript function "requestMore()".

So the above html code becomes:
...
<ul>
  <li>
    <div id="design">Create and Design Databases. (<a href="javascript: requestMore('design')">more...</a>)</div>
  </li>
  <li>
    <div id="data">View/Add/Edit/Delete Database Records. (<a href="javascript: requestMore('data')">more...</a>)</div>
  </li>
  <li>
    <div id="report">Generate Reports. (<a href="javascript: requestMore('report')">more...</a>)</div>
  </li>
  <li>
    <div id="system">Configure System. (<a href="javascript: requestMore('system')">more...</a>)</div>
  </li>
</ul>
It displays like this:










5. Loading Javascript file(s)

I'd like all my javascripts in external file(s). Ramaze provides a simple way to load javascrpt file. For example, I can use js method to load a file that resides at /public/js/ directory like this:
<!-- layout/default.xhtml -->
<!DOCTYPE html>
<html lang="en">
    <head>
       ...
       #{js('myscripts')}      <!-- public/js/myscripts.js -->
    </head>
    ...
But Ramaze layout such as this "default.xml" is called for all pages, and I do not want to load scripts that are not related to particular page that is being displayed. So I use another instance variable (@javascript) that is dynamically updated in order to load different file for different page.
<!-- layout/default.xhtml -->
<!DOCTYPE html>
<html lang="en">
    <head>
       ...
       #{@javascript}
    </head>
    ...
I create one javascript file for each page (controller); for example, home.js file for Home page, data.js file for Data page, and so on.
'


























Each controller updates @javascript variable for each page.
# controller/main.rb
#
class MainController < Controller
  map '/'
  def index
    @subtitle = 'Home'
    @menu = build_menu 'Home'
    @javascript = load_javascript 'Home'
  end
end

class DataController < Controller
  map '/data'
  def index
    @subtitle = 'Data'
    @menu = build_menu 'Data'
    @javascript = load_javascript 'Data' 
  end
end
...

And here is the definition of the load_javascript() method.
class Controller < Ramaze::Controller
  ...
  def load_javascript(current_menu)
    file = current_menu.downcase + ".js"     # main.js, data.js, design.js, system.js
    return ""
  end
end
A resulted html, for example, should look like:




6. Writing Javascript codes that Respond to Event (Simple Test)
Now I can load any javascript file. It is time to write a script that actually responds to an event - a mouse click. First, I write simle codes to test if mouse click gets a response.
/* public/js/home.js */

function requestMore(id)
{
  document.getElementById(id).innerHTML = "Testing " + id + " (less ...)"
}

function requestLess(id)
{
  document.getElementById(id).innerHTML = "Testing " + id + " (more ...)"
}

When "more..." anchor is clicked, it displays the following. It works.

















7. Writing Javascript codes that Respond to Event (AJAX)

A simple test worked. But the content was manually created and not from the server. Now I need to get actual content that comes from the server. To do that, I need to use AJAX. Basically, I create a request object packed with necessary information for obtaining appropriate content and updating part of page. Then I send it to the server which in turn sends back a response object which knows how to update the target area in the page.

This is modified version of home.js.
/* public/js/home.js */

function requestMore(id)
{
 var filename = id + "_more.xhtml"  // design_more.xhtml, data_more.xhtml, etc. 
 
 var request = new XMLHttpRequest();
 request.onreadystatechange=function(){
  if(request.readyState==4 && request.status==200){
   document.getElementById(id).innerHTML = request.responseText;
  }
 }
 request.open("GET", filename,true);
 request.send();
}

function requestLess(id)
{
 var filename = id + "_less.xhtml"  // design_less, data_design, etc
 
 var request = new XMLHttpRequest();
 request.onreadystatechange=function(){
  if(request.readyState==4 && request.status==200){
   document.getElementById(id).innerHTML = request.responseText;
  }
 }
 request.open("GET", filename,true);
 request.send();
}
It retrieves contents of files that reside on server. For example, To display expanded description about Design page, it retrieves design_more.xhtml. To retrieve shorter descrition (default) about Design page, it retrieves design_less.xhtml. And so on.
<!-- public/design_more.xhtml -->
 Create and Design Databases. (<a href="javascript: requestLess('design')">less ...</a>) <br />
 You can create/modify/delete databases. <br />
 You can save/retrieve documents related to database designs.<br />
<!-- public/design_less.xhtml -->
 Create and Design Databases. (<a href="javascript: requestMore('design')">more ...</a>) <br />
Clicking "more..." and "less..." will display the following page as shown back and force.

Saturday, November 5, 2011

Installing git on Ubuntu (11.04)

Installed git.

1 Resorce(s)
http://help.github.com/linux-set-up-git/

2. Installation
Use Synaptic to search and install 'git'

3. Test
$ git --version
git version 1.7.4.1
$ 

4. Start Tracking my App with Git
$ cd ~/public_html/apps/dbmanager
$ git init
Initialized empty Git repository in /home/socrateos/public_html/apps/dbmanager/.git/
$ git add .
$ git commit -m "new app"

Installing Rhino (Javascript shell) on Ubuntu (11.04)

I installed Rhino (Javascript Shell) so that I can test some javascripts interactively just like irb for Ruby.

1. Resource(s)
Mozilla Rhino Project: http://www.mozilla.org/rhino/
Rhino Debugger: http://manpages.ubuntu.com/manpages/natty/man1/rhino-debugger.1.html

2. Installation
Search and install "Rhino" from Ubuntu Software Center.

3. Test
$ js
Rhino 1.7 release 2 2010 11 17
js> "hello".length
5
js> quit()
$ 

Monday, October 24, 2011

Learning Ramaze (3) - Layout and View

I am learning Ramaze, a small web application framework based on Ruby. This is my third post for the topic.

My approach to learning Ramaze is first to (1) start with a skeletal application that Ramaze creates and then (2) modify it manually little by little to achieve a final application that I like; thereby, (3) understanding how Ramaze works along the way. Trying to understand Ramaze through reading its documentation simply does not work for me.

In this post, I describe my changes to the layout (/layout/default.xhtml). The reason for the changes is that I feel uncomfortable about roles of layouts and views so far because the distinction between the two seems somewhat blurred.

1. Resources

Ramaze: http://www.ramaze.net
My first post: Learning Ramaze (1)
My second post: Learning Ramaze (2)


2. Moving Footer Contents out of Layout

I understand that Layout in Ramaze is designed for common parts of multiple views. However, I would like to think that layout is about position, size, color, style and background etc. and that view is about contents such as text and image data. In other words, the role of a layout is about how to display something and the role of a view is about what to display within a given layout.

For example, @content variable is positioned in <body></body> section of the layout (/layout/default.xhtml) and gets replaced with the actual content of its view (/view/index.xhtml) when displayed in browser. The layout is playing a role of presentation and the view is playing a role of contents. That's good.

However, in the footer section of the layout, there are embedded contents such as copyright notice and a "powered by" statement like this:
# /layout/default.xhtml
<footer id="footer">
  Copyright &copy;2011 Socrateos | Powered by <a href="http://ramaze.net/">Ramaze</a>
</footer>
So I moved these contents out of the layout, replacing them with instance variables like this:
# /layout/default.xhtml
<footer id="footer">
  #{@copyright} | #{@poweredby}
</footer>
Then I put those texts in the controller (/controller/main.rb)
# /controller/main.rb
class MainController < Controller
  def index
    @title = 'DBAdmin'
    @subtitle = 'Home'
    @copyright = 'Copyright ©2011 Socrateos'                           # moved here from layout
    @poweredby = 'Powered by <a href=http://www.ramaze.net>Ramaze</a>' # moved here from layout
  end
end

class DataController < Controller
  map '/data' 
  def index
    @title = 'DBAdmin'
    @subtitle = 'Data'
    @copyright = 'Copyright ©2011 Socrateos'                           # moved here from layout
    @poweredby = 'Powered by <a href=http://www.ramaze.net>Ramaze</a>' # moved here from layout
  end
end

class DesignController < Controller
  map '/design'
  def index
    @title = 'DBAdmin'
    @subtitle = 'Design'
    @copyright = 'Copyright ©2011 Socrateos'                           # moved here from layout
    @poweredby = 'Powered by <a href=http://www.ramaze.net>Ramaze</a>' # moved here from layout
  end
end

class SystemController < Controller
  map '/system'
  def index
    @title = 'DBAdmin'
    @subtitle = 'System'
    @copyright = 'Copyright ©2011 Socrateos'                           # moved here from layout
    @poweredby = 'Powered by <a href=http://www.ramaze.net>Ramaze</a>' # moved here from layout
  end
end

Now, these variables never change from page to page. So I do not want to repeat these assignments in every controller. Ramaze actually creates two initial controllers in /controller directory: main.rb and init.rb. And I assume init.rb is called when any controller is instantiated. So if I place these assignment statements in init.rb just once, then it should work for every page. And it does. (I also moved @title here.)
# /controller/init.rb
class Controller < Ramaze::Controller
  ...
  def initialize                        # 2011.10.23 created
    super
    @title = 'DBAdmin'   # 2011.10.23 moved here from main.rb; 2011.09.10 - changed title
    @copyright = 'Copyright ©2011 Socrateos'                           # moved here from layout
    @poweredby = 'Powered by <a href=http://www.ramaze.net>Ramaze</a>' # moved here from layout
  end
end
And controllers in main.rb are now simpler and have no repeating.
# /controller/main.rb
# 2011.10.23 moved variables @titile, @copyright and @poweredby to init.rb#initialize
class MainController < Controller
  map '/'       # Not required, but I prefer explicit statement; it increases clarity of intention.
  def index
    @subtitle = 'Home'
  end
end

class DataController < Controller
  map '/data'
  def index
    @subtitle = 'Data'
  end
end
  
class DesignController < Controller
  map '/design'
  def index
    @subtitle = 'Design'
  end
end

class SystemController < Controller
  map '/system'
  def index
    @subtitle = 'System'
  end
end
3. Moving Navigation Menu Contents out of Layout

The menu items, "Home", "Data", "Design" and "System", are also contents, which I think belong to View, not Layout. So i take them out from the the layout. The layout file /layout/default.xhtml was like this:
...
<nav class="grid_6 last">
<ul class="clearfix">
<li><a href="http://localhost:7000/">Home</></li>
<li><a href="http://localhost:7000/data/">Data</a></li>
<li><a href="http://localhost:7000/design/">Design</a></li>
<li><a href="http://localhost:7000/system/">System</></li>
</ul>
</nav>
...
But now it looks like:
...
<nav class="grid_6 last">
<ul class="clearfix">
#{@menu}    # 2011.10.28 replaced hard-coded menu items. See controller for its content.
</ul>
</nav>
...
Like @title variable, I will initialized @menu variable in the parent controller (in init.rb). I created build_menu() method to generate a text with full menu content. I now use relative paths such as "\data" instead of absolute paths such as "http://localhost:7000/data". I also made a minor change to the title. It is now "Database Manager" instead of "DBAdmin".
# /controller/init.rb
#
class Controller < Ramaze::Controller
  ...
  def initialize
    super
    @title = 'Database Manager' 
    ...
    @menu = build_menu        # 2011.10.28 menu contents set here, removed from layout
  end
  
  def build_menu
    items = {'Home' => '/', 'Data' => '/data', 'Design' => '/design', 'System' => '/system'}
    menu = ''
    items.each do |key,value|
      menu << "<li><a href=\"#{value}\">#{key}</a></li<\n"
    end
    return menu
  end
  
end


4. Underlining Current Menu Item  I have created @subtitle to display which page users are looking at currently. So for example, if user click "Data" menu item, the page displays a big "Data" subtitle. I would like to make a minor change to the menu so that it will underline the current menu, another indication of current page for users. Here is the updated version.
# /controller/init.rb
#
class Controller < Ramaze::Controller
  ...
  def initialize
    super
     ...
    @menu = ''  # 2011.10.29 each controller generates its own menu
  end
  
  def build_menu(current_menu)
    items = {'Home' => '/', 'Data' => '/data', 'Design' => '/design', 'System' => '/system'}
    menu = ''
    items.each do |key,value|
       u1 = (key==current_menu)? '<u>':''
       u2 = (key==current_menu)? '</u>':''
      menu << "<li><a href=\"#{value}\">#{u1}#{key}#{u2}</a></li<\n"
    end
    return menu
  end
  
end
Now I have to generate menu for each controller.
# /controller/main.rb
class MainController < Controller
  map '/'
  def index
    @subtitle = 'Home'
    @menu = build_menu 'Home'
  end
end

class DataController < Controller
  map '/data' 
  def index
    @subtitle = 'Data'
    @menu = build_menu 'Data'
  end
end
data
class DesignController < Controller
  map '/design'
  def index
    @subtitle = 'Design'
    @menu = build_menu 'Design'
  end
end

class SystemController < Controller
  map '/system'
  def index
    @subtitle = 'System'
    @menu = build_menu 'System'
  end
end
And now it looks line this:















5. Summary


1. Layout is used for common parts of multiple views.
2. Layout can also be thought as a presentation layer of display, specifying positions, sizes, and colors and styles whereas views can be thought as contents of display. In other words, layout is about HOW to display; views are about WHAT to display.
3. The menu item contents and footer contents are embedded in a layout in a skeletal app Ramaze creates.
4. One way to remove contents (such as menu items and footer) out of layout is to use instance variables in layout and initialize them in controllers.
5. If the value of instance variable does not change between pages, it can be initialized in the parent controller (Controller#initialize in /controller/init.rb).

6. Next

I have now completed four main pages that correspond to my main menu items: Home, Data, Design, and System. Next I would like to learn how to control and display the body part of each of these pages.

Saturday, October 22, 2011

Learning Ramaze (2) - Adding More Pages

I am learning Ramaze, a small Ruby web framework. This post continues what I started in the previous post, Learning Ramaze (1).

As described in my previous post, my approach to learn Ramaze is to start with a skeletal Ramaze app and to make changes bit by bit to my liking, learning how Ramaze works along the way.

In this second post, I describe what I did to add more pages to the application.
My navigation menu has 4 items: Home, Data, Design, System. I want separate pages for these menu items.

Basically, I create a controller and a view file for each of these three new pages. Ramaze then takes care of the rest.


1. Resources

Ramaze: http://www.ramaze.net
Learning Ramaze (1): My previous post that started Leaning Ramaze series.



2. Display Page Title


Currently the instant variable @tile is used to display the title, "DBAdmin". Since the application is going to have multiple pages, I want to display a page title also. Then, I will know immediately which page I am looking at. To do this, I edited /layout/default.xhtml and added a new instance variable @subtitle, which can be "Home", "Data", "Design" or "System".

# /lauout/default.xhtml

  <head>
    <title>#{@title}/#{@subtitle}</title> # added subtitle
    ...
    </head>
  <body>
    ...
    <header class="grid_6">
      <h2>#{@title}</h2>                  # used for application title (in smaller font)
      <h1>#{@subtitle}</h1>               # added to display current page (in larger font)
    </header> 
  ... 
So the header section of a page looks like this:






3. Create Controllers For New Pages

Edit /controller/main.rb to add controllers for new pages: DataController, DesignController, and SystemController. Note that I added @subtitle variable to display user's current page (menu).


# /controller/main.rb

class MainController < Controller
...  
 def index
    @title = 'DBAdmin'
    @subtitle = 'Home'     # display current page in multi-page application/site
  end
...
end


class DataController < Controller
  map '/data'               
  
  def index                # Ramaze will find its content in /view/data/index.xhtml
    @title = 'DBAdmin'
    @subtitle = 'Data'     # display current page in multi-page application/site
  end
  
end


class DesignController < Controller
  map '/design'
  
  def index                # Ramaze will find its content in /view/design/index.xhtml
    @title = 'DBAdmin'
    @subtitle = 'Design'   # display current page in multi-page application/site
  end
  
end


class SystemController < Controller
  map '/system'
  
  def index                # Ramaze will find its content in /view/system/index.xhtml
    @title = 'DBAdmin'
    @subtitle = 'System'   # display current page in multi-page site
  end
  
end


4. Create View Files For New Page Contents

Now I create view files, one for each of new pages to display its contents.
All these four files have same name, index.xhtml, and placed in its own sub-folder under /view folder. For example, the data view file (index.xhtml) will be placed in /view/data.

So my view directory becomes like this:















And each view file looks like the followings:
# view/data/index.xhtml

<p>
    DBAdmin is a web tool to manage PostgreSQL databases.
</p>

<p>
    Here we can: View/Add/Edit/Delete Database Records
</p>

<ul>
    <li>
       View - displays query results
    </li>
    <li>
       Add - add new record(s)
    </li>
    <li>
       Edit - modify existing record(s)
    </li>
    <li>
       Delete - delete record(s)
    </li>
</ul>
# view/design/index.xhtml

<p>
    DBAdmin is a web tool to manage PostgreSQL databases.
</p>

<p>
    Here we can design database structure.
</p>

<ul>
     <li>
       Databases - create, alter, drop database(s)
     </li>
     <li>
       Tables - create, alter, drop table(s)
     </li>
     <li>
       Roles - create, alter, drop role(s)
     </li>
</ul>
# view/system/index.xhtml

<p>
    DBAdmin is a web tool to manage PostgreSQL databases.
</p>

<p>
    Here we can modify web interface.
</p>

<ul>
    <li>
       UI Templates - select preferred UI template
    </li>
    <li>
       Add-Ons - add new capabilities through add-ons
    </li>
    <li>
       Etc.
    </li>
</ul>



5. Results of Changes

Here are the results of the changes.




















6. Another way

Instead of creating controllers, sub-folders and index.xhtml files,I could have used additional methods within MainController and created corresponding view files in the same /view folder.

# /controller/main.rb
#
class MainController < Controller

  def index
    @title = 'DBAdmin'
    @subtitle = 'Home'
  end
  
  def data
    @title = 'DBAdmin'
    @subtitle = 'Data'
  end

  def design
    @title = 'DBAdmin'
    @subtitle = 'Design'
  end

  def system
    @title = 'DBAdmin'
    @subtitle = 'System'
  end

end
Then I would create the corresponding view files (data.xhtml, design.xhtml, and system.xhtml) placed directly in /view directory without sub-folders.

 This is much simpler. But using of controllers and sub-view folders is perhaps more scalable. Since my DBAdmin is going to be rather complex, I decided to use controllers and sub-folders for these main pages. Besides, a well-organized sub-directories of view gives an instant preview of basic structure of the application/site.


7. Summary

1. There are at least two way of creating multiple pages (besides static files).
2. One way of creating multiple pages is to use controllers, sub-view folders.
3. Another way of creating multiple pages is to use additional methods within the /controller/main.rb and corresponding view files directly under the /view directory.
4. Using of additional methods has advantage of simplicity.
5. Using controllers and sub-view folders has advantage of scalability.
6. Using controllers and sub-view folders has also advantage of providing an instant preview of basic structure of application/site.


8. Next

There are a few things that I would like to modify. For example, I initialize @title to "DBAdmin" - four times. Since the value of the variable never changes, its initialization should be done only once. Another thing that I would like to change is about usage of layout. Currently distinction between layout and view is blurred. I would like to make a clear distinction so that layout is used for display framework only and its view for contents only.

Tuesday, October 18, 2011

Installing Aptana Studio 3 on Ubuntu 11.04

I installed Aptana Studio 3 on my Ubuntu 11.04.

1. Resources.
Aptana home: http://www.aptana.com/

2. Install.
Downloaded Aptana Studio 3.
Unzipped to a folder "Aptana Studio 3"
Dropped the folder in /opt/ directory
Renamed the folder to "aptana3"

3. Placed a link in the Main Menu.

Sunday, October 16, 2011

Reinstalling Sequel

My installed Sequel was acting strange. It crashed hard to corrupt my file systems, resulting my Ubuntu not being able to start up. So I decided to reinstall it.


0. Resources
Sequel home page: http://sequel.rubyforge.org/


1. Uninstall Sequel
$ sudo gem uninstall sequel
Select gem to uninstall:
 1. sequel-3.26.0
 2. sequel-3.27.0
 3. All versions
> 3
Successfully uninstalled sequel-3.26.0
Successfully uninstalled sequel-3.27.0

2. Install Sequel
$ sudo gem install sequel
Successfully installed sequel-3.28.0
1 gem installed
Installing ri documentation for sequel-3.28.0...
Installing RDoc documentation for sequel-3.28.0...

3. Test Sequel
$ irb
irb(main):001:0> require 'sequel'
=> true
irb(main):002:0> DB = Sequel.sqlite
=> #
irb(main):003:0> DB.create_table :items do
irb(main):004:1* primary_key :id
irb(main):005:1> String :name
irb(main):006:1> Float :price
irb(main):007:1> end
=> nil
irb(main):008:0> items = DB[:items]
=> #
irb(main):009:0> items.insert(:name => 'iphone', :price => 450)
=> 1
irb(main):010:0> items.insert(:name => 'xphone', :price => 550)
=> 2
irb(main):011:0> items.insert(:name => 'zphone', :price => 650)
=> 3
irb(main):012:0> puts "Items count: #{items.count}"
Items count: 3
=> nil
irb(main):013:0> puts "Average price is: #{items.avg(:price)}"
Average price is: 550.0
=> nil

4. Test Sequel (continues)
irb(main):014:0> PGDB = Sequel.connect('postgres://localhost/mydb?user=socrateos&password=secret')
=> #
irb(main):015:0> PGDB.create_table :items do
irb(main):016:1* primary_key :id
irb(main):017:1> String :name
irb(main):018:1> Float :price
irb(main):019:1> end
=> nil
irb(main):020:0> pgitems = PGDB[:items]
=> #
irb(main):021:0> pgitems.insert(:name => 'Camera A', :price => 1000)
=> 1
irb(main):022:0> pgitems.insert(:name => 'Camera B', :price => 2000)
=> 2
irb(main):023:0> pgitems.insert(:name => 'Camera C', :price => 3000)
=> 3
irb(main):024:0> puts "Item count: #{pgitems.count}"
Item count: 3
=> nil
irb(main):025:0> puts "Average price: #{pgitems.avg(:price)}"
Average price: 2000.0
=> nil

5. Finish Testing Sequel
irb(main):026:0> DB.disconnect
=> []
irb(main):027:0> PGDB.disconnect
=> []
irb(main):028:0> quit

Saturday, October 1, 2011

Installing Ruby (Ruboto) on Sony Tablet S

I installed Ruboto (JRuby for Android) on Sony Tablet S.

1. Resouces.
Ruboto: http://ruboto.org/
Running a Ruby interpreter on iPad: http://stackoverflow.com/questions/2602697/running-a-ruby-interpreter-on-ipad

2. Installing Ruboto-IRB on the Sony Tablet.
It's so simple to install Ruboto-IRB.
(1) Go to the Market and search for Ruboto. 
(2) Download Ruboto-IRB.
(3) Open installed Ruboto-IRB
(4) Wait to see "Installing JRuby .... Done"
That's it.

3. Testing the IRB.
>> "Hello World" [Enter]
==> Helo World
>> 1+2 [Enter]
==> 3
>> s = "Ruby string" [Enter]
==> Ruby string
>> s.upcase [Enter]
==> RUBY STRING
Nice!

Saturday, September 10, 2011

Learning Ramaze (1) - Changing title and Background

I would like to learn how to use Ramaze framework. My approach is to start with the default app it creates. Then bit by bit, I modify it to my liking, learning the framework along the way.



1. Resources.


Ramaze: http://www.ramaze.net


2. Create a new Ramaze app.


I would like to create a web app to manage PostgreSQL databases.
So I named my app "dbadmin".
$ cd ~/public_html/apps/                                   # switch to apps folder
$ ramaze create dbadmin                                    # create a ramaze app "dbadmin"
The application has been generated and saved in dbadmin
$ cd dbadmin/                                              # go into the newly created app root
$ ls                                                       # view all default files/directories created
app.rb  config.ru  controller  layout  model  public  spec  start.rb  view
$ ramaze console                                           # launch ramaze console
irb(main):001:0> Ramaze.options.app.name                   # test a ramaze command
=> :pristine                                               # what is pristine?
irb(main):002:0> quit                                      # exit from ramaze console
Ramazement has ended, go in peace.
$
This is the directory of a newly created Ramaze app:























3. Personalizing Ramaze app (Title and Footer).


First, I edit /controller/main.rb to make a title change from "Welcome to Ramaze!" to "DBAdmin".
# /controller/main.7. Now It Looks Like This.rb
#
class MainController < Controller
  def index
    @title = 'DBAdmin'         # 2011.09.10 - changed title
  end

  def notemplate
    @title = 'DBAdmin'         # 2011.09.10 - changed title
    return 'There is no \'notemplate.xhtml\' associated with this action.'
  end
end
Next, I edit /layout/default.xhtml to make changes in footer as follows.
<footer id="footer">
  Copyright &copy;2011 Socrateos | Powered by <a href="http://ramaze.net/">Ramaze</a>
</footer>


4. Personalizing Ramaze app (Background).


I want my background white and most texts black. I want a really simple style.

(A) First, I remove Ramaze's default background (dotted) image.
To do this, I edit /public/css/text.css.
body
{
    <!-- 2011.09.09 - remove default background image
    background:  url('../images/bg.png') repeat top left;
    -->
    border-top:  5px solid #444;
    color:       #444;
    font-family: 'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, sans-serif;
    font-size:   14px;
}
(B) Second, I want to change the background of the header section
I want to make background color of the header to white, same as the page background.
Since background becomes white, the color of text in the header can no longer be white.
So I edit /public/css/layout.css for the changes.
/* Top part of the website, contains the title and the navigation menu */
#top
{
    /* 2011.09.10 - changed to white backgroud
    background:    #E33F1E;
    */
    background: #fff; 
    height:        70px;
    margin-bottom: 20px;
    padding:       0px 10px;
}

    #top header h1
    {
        /* 2011.09.10 - cannot use white color for text since background is now white
        color:       #fff;
        */ 
        font-size:   38px;
        margin:      10px 0px 0px 0px;
        padding:     0px;
    }
...
            #top nav ul li a
            {
                /* 2011.09.10 - cannot use white color for text since background is now white
                color:           #fff;
                */ 
                display:         block;
                height:          45px;
                padding:         25px 10px 0px 10px;
                text-decoration: none;
            }
In addition, I do not like the square background color when the cursor moves on navigation items.
So I remove it.
...
            #top nav ul li a:hover
            {
                /* 2011.09.10 - remove this color 
                background: #D43919; 
                */ 
            }


5. So far, It Looks Like This.





















6. Personalizing Ramaze app (contents)

Now I modify the contents, both navigation menu bar as well as its body.

(A) Modifying Navigation menu bar.
To make a change to the navigation menus, I edit /layout/default.xhtml. My navigation menu bar has 4 main items: Home, Data, Desin, and System.

...

...

(B) Modifying Body of Contents.
To make changes in the body of contents, I edit /view/index.xhtml.

DBAdmin is a web tool to manage PostgreSQL databases.

Features:

  • Create and Design Databases.
  • View/Add/Edit/Delete Database Records.
  • Generate Reports.
  • Configure System.
DBAdmin is based on Ramaze.


7. Now It Looks Like This.


















8. Summary.

1. To create a skeletal Ramaze app, execute $ ramaze create myapp.
2. To change the page title, edit the value of @title variable in /controller/main.rb.
3. To change the footer, edit the <footer></footer> section in /layout/default.xhtml.
4. To change the background image, edit body{background:...} section in /public/css/text.css.
5. To change the text and background color of the header section, edit edit /public/css/layout.css.
6. To change the navigation menu, edit the <nav></nav> section in /layout/default.xhtml.
7. To change the body contents, edit /view/index.xhtml.

9. Next Step

I only made changes to the main (home) page so far. Next, I want to create other pages: Data, Design, and System pages.
Goto: Learning Ramaze (2) - Adding More Pages

Fixing File System error on startup

I had a bad crash that damaged my filesystem. And my Ubuntu was not starting.
I needed to fix the file system.

1. Start with CD version of Ubuntu.
2. Open the Terminal.
3. List the all disk devices.
$ sudo fdisk -l
Disk /dev/sda: 1000.2 GB, 1000204886016 bytes
...
Device   Boot       Start         End       Block   Id  System
/dev/sda1   *           1      121602   976759808    7  HPFS/NTFS
...
Disk /dev/sdb: 1000.2 GB, 1000204886016 bytes
...
Device   Boot       Start         End       Block   Id  System
/dev/sdb1               1      121602   976759808    7  HPFS/NTFS
...
Disk /dev/sdc: 1000.2 GB, 1000204886016 bytes
...
Device   Boot       Start         End       Block   Id  System
/dev/sdc1               1      121602   976759808    7  HPFS/NTFS
...
Disk /dev/sdd: 1000.2 GB, 1000204886016 bytes
...
Device   Boot       Start         End       Block   Id  System
/dev/sdd1               1      119825   962492416   83  Linux
/dev/sdd2          119826      121602    14267393    5  Extended
/dev/sdd5          120331      121602    10206208   82  Linux swap / Solaris
/dev/sdd6          119826      120331     4061184   82  Linux swap / Solaris

Partition table entries are not in disk order
My Ubuntu is installed on the 4th disk (/dev/sdd), which is damaged.

4. Fix the 4th Disk
$ sudo umount /dev/sdd1      # unmount just in case
$ sudo fsck /dev/sdd1        # fix errors
...                          # hit y(es) several times to allow fixing..

It worked.I was able to start Ubuntu as usual.

Sunday, September 4, 2011

Setting up User for PostgreSQL

I do not like using superuser 'postgres' as daily database management.
So I want to add my account name 'socrateos' as a postgresql user.

$ su postgres                                             # switch to user postgres
$ psql                                                    # launch psql client
psql (9.0.4)
postgres=# CREATE ROLE socrateos WITH CREATEDB CREATEROLE LOGIN PASSWORD 'secret'; # a new user
CREATE ROLE
postgres=# CREATE DATABASE testdb;                        # create a new database
CREATE DATABASE
postgres=# \q                                             # quit psql
$ exit                                                    # exit from user postgres 
exit
$ whoami                                                  # be sure I am back to myself
socrateos                                                 # yes, I am in my own account
$ psql testdb                                             # now login to postgresql as myself
testdb=> CREATE DATABASE mydb;                            # I can create a database
CREATE DATABASE
testdb=> \c mydb;                                         # connect to the newly created database
You are now connected to database "mydb".
mydb=> CREATE TABLE table1(id SERIAL PRIMARY KEY, name VARCHAR(32)); # test creating a table
CREATE TABLE
mydb=> INSERT INTO table1(name) VALUES('john');           # insert a row
INSERT 0 1
mydb=> INSERT INTO table1(name) VALUES('mary');           # insert another row
INSERT 0 1
mydb=> SELECT * FROM table1;                              # list all rows
 id | name 
----+------
  1 | john
  2 | mary
mydb=> \q                                                 # done with the test and quit psql

OK, so I think I am ready to manage PostgreSQL without using superuser 'postgres'.

Saturday, September 3, 2011

Installing Zen CMS on Ubuntu (11.04)

I stumbled upon a new CMS based on Ruby/Ramaze. It is called Zen (http://zen-cms.com/). Since I have recently switched to Nginx/Unicorn Web environment and found that Ramaze works without any hick up in that environment, I decided to check it out. The following is how I installed it.

1. Resources.
Zen • The Modular CMS: http://zen-cms.com/
Ramaze: http://ramaze.net/
Running a Rack app (Ramaze) with Nginx/Unicorn: http://socrateos.blogspot.com/search/label/unicorn

2. Requirements.
Ruby 1.9.2 (MRI) - This is my default ruby.
Ramaze 2011.01.30 - I recently installed on my Ubuntu
A SQL database supported by Sequel - I am using PostgeSQL.
A Rack server (Thin, Unicorn or Mongrel) - I am using Unicorn.
Libraries required for Nokogiri: libxml2, libxml2-dev, libxslt-dev (libxslt1-dev was one that I found and installed, using Synaptic)

3. Installation.
$ sudo gem install zen
Building native extensions.  This could take a while...
Successfully installed nokogiri-1.5.0
Successfully installed loofah-1.0.0
Successfully installed zen-0.2.8
3 gems installed
Installing ri documentation for nokogiri-1.5.0...
Installing ri documentation for loofah-1.0.0...
Installing ri documentation for zen-0.2.8...
Installing RDoc documentation for nokogiri-1.5.0...
Installing RDoc documentation for loofah-1.0.0...
Installing RDoc documentation for zen-0.2.8...

4. Create Zen Application
$ zen create app2
The application has been generated and saved in app2
$ cd app2/
$ ls
Rakefile  app.rb  config  config.ru  log  public  start.rb  task  theme

5. Setup Config.
The following is my settings for database.rb.
Zen.database = Sequel.connect(
  :adapter  => 'postgres',
  :host     => 'localhost',
  :username => 'socrateos',     # I have createdb, createrole rights
  :password => 'secret',
  :database => 'app2',
  :test     => true,
  :encoding => 'utf8',
  :logger   => Ramaze::Logger::RotatingInformer.new(
    __DIR__("../log/database/dev"), '%d-%m-%Y.log'
  )
)

# IMPORTANT, when running MySQL the engine should be set to InnoDB in order for
# foreign keys to work properly.
if Zen.database.adapter_scheme.to_s.include?('mysql')
  Sequel::MySQL.default_engine = 'InnoDB'
end

6. Failed to Rake DB:Migrate
I ran rake db:migrate. But it failed.
$ rake db:migrate --trace
W [2011-09-06 22:57:42 $2563]  WARN | : Failed to migrate the settings, make sure the database table is up to date
** Invoke db:migrate (first_time)
** Execute db:migrate
rake aborted!
PGError: ERROR:  ...
/var/lib/gems/1.9.1/gems/sequel-3.26.0/lib/sequel/adapters/postgres.rb:186:in `async_exec'
/var/lib/gems/1.9.1/gems/sequel-3.26.0/lib/sequel/adapters/postgres.rb:186:in `block (2 levels) in execute'
/var/lib/gems/1.9.1/gems/sequel-3.26.0/lib/sequel/database/logging.rb:32:in `log_yield'
/var/lib/gems/1.9.1/gems/sequel-3.26.0/lib/sequel/adapters/postgres.rb:186:in `block in execute'
/var/lib/gems/1.9.1/gems/sequel-3.26.0/lib/sequel/adapters/postgres.rb:166:in `check_disconnect_errors'
/var/lib/gems/1.9.1/gems/sequel-3.26.0/lib/sequel/adapters/postgres.rb:186:in `execute'
/var/lib/gems/1.9.1/gems/sequel-3.26.0/lib/sequel/adapters/postgres.rb:256:in `block (2 levels) in execute'
/var/lib/gems/1.9.1/gems/sequel-3.26.0/lib/sequel/connection_pool/threaded.rb:71:in `hold'
/var/lib/gems/1.9.1/gems/sequel-3.26.0/lib/sequel/database/connecting.rb:226:in `synchronize'
/var/lib/gems/1.9.1/gems/sequel-3.26.0/lib/sequel/adapters/postgres.rb:256:in `block in execute'
/var/lib/gems/1.9.1/gems/sequel-3.26.0/lib/sequel/adapters/postgres.rb:277:in `check_database_errors'
/var/lib/gems/1.9.1/gems/sequel-3.26.0/lib/sequel/adapters/postgres.rb:254:in `execute'
/var/lib/gems/1.9.1/gems/sequel-3.26.0/lib/sequel/database/query.rb:71:in `execute_dui'
/var/lib/gems/1.9.1/gems/sequel-3.26.0/lib/sequel/database/query.rb:64:tin `execute_ddl'
/var/lib/gems/1.9.1/gems/sequel-3.26.0/lib/sequel/database/schema_methods.rb:372:in `create_table_from_generator'
/var/lib/gems/1.9.1/gems/sequel-3.26.0/lib/sequel/database/schema_methods.rb:97:in `create_table'
/var/lib/gems/1.9.1/gems/sequel-3.26.0/lib/sequel/extensions/migration.rb:629:in `schema_dataset'
/var/lib/gems/1.9.1/gems/sequel-3.26.0/lib/sequel/extensions/migration.rb:382:in `initialize'
/var/lib/gems/1.9.1/gems/sequel-3.26.0/lib/sequel/extensions/migration.rb:542:in `initialize'
/var/lib/gems/1.9.1/gems/sequel-3.26.0/lib/sequel/extensions/migration.rb:333:in `new'
/var/lib/gems/1.9.1/gems/sequel-3.26.0/lib/sequel/extensions/migration.rb:333:in `run'
/var/lib/gems/1.9.1/gems/zen-0.2.8/lib/zen/task/db.rake:28:in `block (4 levels) in '
/var/lib/gems/1.9.1/gems/sequel-3.26.0/lib/sequel/database/query.rb:231:in `_transaction'
/var/lib/gems/1.9.1/gems/sequel-3.26.0/lib/sequel/database/query.rb:210:in `block in transaction'
/var/lib/gems/1.9.1/gems/sequel-3.26.0/lib/sequel/connection_pool/threaded.rb:84:in `hold'
/var/lib/gems/1.9.1/gems/sequel-3.26.0/lib/sequel/database/connecting.rb:226:in `synchronize'
/var/lib/gems/1.9.1/gems/sequel-3.26.0/lib/sequel/database/query.rb:208:in `transaction'
/var/lib/gems/1.9.1/gems/zen-0.2.8/lib/zen/task/db.rake:27:in `block (3 levels) in '
/var/lib/gems/1.9.1/gems/zen-0.2.8/lib/zen/task/db.rake:12:in `each'
/var/lib/gems/1.9.1/gems/zen-0.2.8/lib/zen/task/db.rake:12:in `block (2 levels) in '
/var/lib/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:205:in `call'
/var/lib/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:205:in `block in execute'
/var/lib/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:200:in `each'
/var/lib/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:200:in `execute'
/var/lib/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:158:in `block in invoke_with_call_chain'
/usr/lib/ruby/1.9.1/monitor.rb:201:in `mon_synchronize'
/var/lib/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:151:in `invoke_with_call_chain'
/var/lib/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:144:in `invoke'
/var/lib/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:112:in `invoke_task'
/var/lib/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:90:in `block (2 levels) in top_level'
/var/lib/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:90:in `each'
/var/lib/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:90:in `block in top_level'
/var/lib/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:129:in `standard_exception_handling'
/var/lib/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:84:in `top_level'
/var/lib/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:62:in `block in run'
/var/lib/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:129:in `standard_exception_handling'
/var/lib/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:59:in `run'
/var/lib/gems/1.9.1/gems/rake-0.9.2/bin/rake:32:in `'
/var/lib/gems/1.9.1/bin/rake:19:in `load'
/var/lib/gems/1.9.1/bin/rake:19:in `
' Tasks: TOP => db:migrate

Friday, August 26, 2011

Installing Sequel on Ubuntu (11.04)

Installed sequel on my Ubuntu (11.04).

$ sudo gem install sequel
Successfully installed sequel-3.26.0
1 gem installed
Installing ri documentation for sequel-3.26.0...
Installing RDoc documentation for sequel-3.26.0...
$ sequel -v
sequel 3.26.0
$ irb
irb(main):001:0> require 'sequel'
=> true
irb(main):002:0> exit

Sunday, August 21, 2011

Installing Shotgun (Ruby Gem) on Ubuntu (11.04)

Installed shotgun on my Ubuntu (11.04).

1. Resources.

http://ruby.about.com/od/sinatra/a/sinatra5.htm

2. Installation.

$ sudo gem install shotgun
Successfully installed shotgun-0.9
1 gem installed
Installing ri documentation for shotgun-0.9...
Installing RDoc documentation for shotgun-0.9...
$ irb
irb(main):001:0> require 'shotgun'   # check the installation
=> true
irb(main):002:0> exit

Installing Sinatra on Ubuntu (11.04)

I installed sinatra, a lightweight web framework, on my Ubuntu (11.04).

1. Resources

Sinatra Ruby: http://www.sinatrarb.com/

2. Installation.

$ sudo gem install sinatra
Successfully installed tilt-1.3.2        # what is this?
Successfully installed sinatra-1.2.6
2 gems installed
Installing ri documentation for tilt-1.3.2...
Installing ri documentation for sinatra-1.2.6...
Installing RDoc documentation for tilt-1.3.2...
Installing RDoc documentation for sinatra-1.2.6...
$ irb
irb(main):001:0> require 'sinatra'      # check installation
=> true
irb(main):002:0> exit

3. What is Tilt?

The sinatra installer installed tilt. What is tilt?
According to the tilt site, it is "a thin interface over a bunch of different Ruby template engines in an attempt to make their usage as generic possible." It seems to support a very large number of template engines, including ERB, Haml, Erubis, Maruku, Radius, RedCloth, BlueCloth, etc.

Installing SQLite3 for Ruby on Ubuntu 11.4

Install SQL commandline interface and interface library for Ruby 1.9.1


1. Resources.

SQLite Home Page: http://www.sqlite.org/

2. Install SQLite3 Libraries and a commandline interface.

Open Synaptic Package Manager
Find and install the following:
-- sqlite3
-- libsqlite3-ruby1.9.1
-- libsqlite3-dev



3.Test sqlite3 commandline interface.

$ sqlite3 --version
3.7.4

4. Install sqlite3 gem.

Note that sqlite3-ruby is now obsolete. The sqlite3-ruby is now called "sqlite3". The sqlite3-ruby is now a dummy gem that depends on sqlite3. (See here.)

$ sudo gem install sqlite3
Building native extensions.  This could take a while...
Successfully installed sqlite3-1.3.4
1 gem installed
Installing ri documentation for sqlite3-1.3.4...
Installing RDoc documentation for sqlite3-1.3.4...
Test the gem installation.
$ irb
irb(main):001:0> require 'sqlite3'
=> true
irb(main):002:0> exit


Sunday, August 14, 2011

Running a Rack app (Ramaze) with Nginx/Unicorn on Ubuntu (11.04)

I want to setup a Rack app on a virtual host on my Ubuntu 11.04 for my tiny intranet. I am already running multiple virtual hosts (www.domain1.com and www.domain2.com) on my Ubuntu. This time, I want to add another virtual host (www.domain3.com) that invokes a Rack application.



1. Requirements.

Ubuntu - a Linux distribution
Ruby - a scripting language
Nginx - a web server that handles multiple virtual hosts
Unicorn - web server to be used to runs behind Nginx
Ramaze - a Rack web framework ("Mini Rails")


2. Resources.

Nginx: http://wiki.nginx.org/
Unicorn: http://unicorn.bogomips.org/
Ramaze: http://ramaze.net/
Silpsen: Setting up Unicorn with Nginx
slicehost: Ubuntu Intrepid - Nginx, rails and mongrels
slicehost: Ubuntu Intrepid - Nginx, rails and thin
Tom Kersten: Setting up Ubuntu with Nginx, Unicorn, ree, rv
Maxime Rousseaux-Bridle blog: Running Ramaze with Unicorn, Nginx and God


3. Create a virtual host.
My ultimate goal is to create a virtual host (www.domain3.com) to run my Rack app (Ramaze). But first I create a normal virtual host (www.domain3.com), without running any web app. Later I will create a web app, which will take over the control of incoming requests.

The first step to create a virtual host is to crate a directory structure and place an index.html file in its public folder.
$ mkdir ~/public_html/domain3.com
$ mkdir ~/public_html/domain3.com/{public,private,log,backup}
$ gedit ~/public_html/domain3.com/public/index.html   # create home index.html file
It's content looks like this:
<html>
  <head>
    <title>domain3.com</title>
  </head>
  <body>
    <h1>domain3.com</h1>
  </body>
</html>
Then I create a normal virtual host file for Nginx. Later I will modify it to redirect its requests to my Rack (Ramaze) app.
$ sudo gedit /etc/nginx/sites-available/domain3.com
Here is it's content.
server {
            listen   80;
            server_name  www.domain3.com;
            rewrite ^/(.*) http://domain3.com/$1 permanent;
           }

server {
            listen   80;
            server_name domain3.com;

            access_log /home/socrateos/public_html/domain3.com/log/access.log;
            error_log /home/socrateos/public_html/domain3.com/log/error.log;

            location / {
                        root   /home/socrateos/public_html/domain3.com/public/;
                        index  index.html;
                        }
            }
Now enable the host, by creating a symlink file into /etc/nginx/sites-enabled directory.
$ sudo ln -s /etc/nginx/sites-available/domain3.com /etc/nginx/sites-enabled/domain3.com
Finally update the /etc/hosts file by adding a new domain name. (My tiny intranet does not need/use DNS.) I just manually edit hosts file in each PC.
127.0.1.1 domain1.com
127.0.1.1 www.domain1.com
127.0.1.1 domain2.com
127.0.1.1 www.domain2.com
127.0.1.1 domain3.com          # new domain added to be used for Ramaze app
127.0.1.1 www.domain3.com      # new domain added to be used for Ramaze app
I added similar entries to C:\Windows\System32\drivers\etc\hosts on my Windows Visita.
192.168.12.13 domain1.com
192.168.12.13 www.domain1.com
192.168.12.13 domain2.com
192.168.12.13 www.domain2.com  
192.168.12.13 domain3.com      # new domain added to be used for Ramaze app
192.168.12.13 www.domain3.com  # new domain added to be used for Ramaze app
Restart my Nginx server.
$ sudo /etc/init.d/nginx stop
Stopping nginx: nginx.
$ sudo /etc/init.d/nginx start
Starting nginx: nginx.
Now test http://www.domain3.com with my browser.
The result looks like this as expected. So my new virtual host is working.
















4. Create a Rack App (Ramaze)

I now build a Rack (Ramaze) app. Then do a quick test run with Unicorn server, without going through Nginx.
$ cd ~/public_html/      
$ mkdir apps/          # a parent directory for all my web apps
$ cd apps/
$ ramaze create app1   # create a Ramaze app
The application has been generated and saved in app1
$ cd app1/
$ mkdir tmp            
$ mkdir tmp/pids       # for unicorn master pid
$ mkdir log            # for nginx and unicorn logs
$ unicorn              # a quick test run with unicorn server
I, [2011-08-08T00:08:11.149051 #3759]  INFO -- : listening on addr=0.0.0.0:8080 fd=3
I, [2011-08-08T00:08:11.149263 #3759]  INFO -- : worker=0 spawning...
I, [2011-08-08T00:08:11.149838 #3759]  INFO -- : master process ready
I, [2011-08-08T00:08:11.150249 #3761]  INFO -- : worker=0 spawned pid=3761
I, [2011-08-08T00:08:11.150372 #3761]  INFO -- : Refreshing Gem list
I, [2011-08-08T00:08:11.480209 #3761]  INFO -- : worker=0 ready
Here is the result from http://localhost:8080, directly accessing Unicorn server. Later, after I setup Unicorn to run behind Nginx, I will access our app from http://www.domain3.com, where my nginx server transfers control to Unicorn server, which actually serves our web app.


















5. Make Unicorn run behind Nginx

At this point, I have two web servers running independently: Nginx (for a few virtual domains) at port 80 and Unicorn (for Ramaze app) at port 8080. I am now going to modify the configuration of one of nginx's virtual domains (domain3.com) so that Ngix will transfer control to Unicorn if web requests are for this the domain. In other words, Unicorn will be working as a server behind the Nginx server.
sudo gedit /etc/nginx/sites-available/domain3.com    # open the domain3.com (conf) file for editing.
Here is the modified contents. This is based on slicehost's "Ubuntu Intrepid - Nginx, rails and thin".
upstream backend {
        server 127.0.0.1:8080;
    }

server {
            listen   80;
            server_name  www.domain3.com;
            rewrite ^/(.*) http://domain3.com/$1 permanent;
           }


server {
            listen   80;
            server_name domain3.com;

            access_log /home/socrateos/public_html/apps/app1/log/access.log;
            error_log /home/socrateos/public_html/apps/app1/log/error.log;

            root   /home/socrateos/public_html/apps/app1/public/;
            index  index.html;

            location / {
                          proxy_set_header  X-Real-IP  $remote_addr;
                          proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
                          proxy_set_header Host $http_host;
                          proxy_redirect off;

                          if (-f $request_filename/index.html) {
                                           rewrite (.*) $1/index.html break;
                          }

                          if (-f $request_filename.html) {
                                           rewrite (.*) $1.html break;
                          }

                          if (!-f $request_filename) {
                                           proxy_pass http://backend;
                                           break;
                          }
            }

}

Restart Nginx.
$ sudo /etc/init.d/nginx stop
Stopping nginx: nginx.
$ sudo /etc/init.d/nginx status
 * could not access PID file for nginx
$ sudo /etc/init.d/nginx start
Starting nginx: nginx.
Then go to http://www.domain3.com. And Voila! We are now seeing a Rack app running under Unicorn server behind a Nginx web server.

















6. Daemonize Unicorn


The last step is to run Unicorn as a daemon and start it when Ubuntu starts up. To do this, first, I create a new conf file for Unicorn. I will name it unicorn.conf and place it in app's root directory.
gedit ~/public_html/apps/app1/unicorn.conf
The following is its contents. It is based on http://unicorn.bogomips.org/examples/unicorn.conf.rb and "Running Ramaze with Unicorn, Nginx and God" by Maxime Rousseaux-Bridle. For a detailed information, see Unicorn::Configurator.

# unicorn.conf
# (ruby code)
# Based on the following examples: 
# http://unicorn.bogomips.org/examples/unicorn.conf.rb
# http://blog.xambr.com/2010/01/16/running-ramaze-with-unicorn-nginx-and-god/


APP_ROOT = "/home/socrateos/public_html/apps/app1"

worker_processes 4
working_directory APP_ROOT

# listen on both a Unix domain socket and a TCP port
listen "{APP_ROOT}/tmp/unicorn.sock", :backlog => 64
listen 8080, :tcp_nopush => true

# Location of master process PID file
pid "#{APP_ROOT}/tmp/pids/unicorn-master.pid"

# Location of stderr/stdout logs
stderr_path "#{APP_ROOT}/log/unicorn.stderr.log"
stdout_path "#{APP_ROOT}/log/unicorn.stdout.log"

# combine REE with "preload_app true" for memory savings
# http://rubyenterpriseedition.com/faq.html#adapt_apps_for_cow
preload_app true
GC.respond_to?(:copy_on_write_friendly=) and
GC.copy_on_write_friendly = true

Next, I create an init script file unicorn and placed it in /etx/init.d/ directory to launch Unicorn as a daemon.
#! /bin/sh

# File: /etc/init.d/unicorn

### BEGIN INIT INFO
# Provides:          unicorn
# Required-Start:    $local_fs $remote_fs $network $syslog
# Required-Stop:     $local_fs $remote_fs $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts the unicorn web server
# Description:       starts unicorn
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/var/lib/gems/1.9.1/bin/unicorn
DAEMON_OPTS="-c /home/socrateos/public_html/apps/app1/unicorn.conf -E production -D"
NAME=unicorn
DESC="Unicorn app for app1"
PID=/home/socrateos/public_html/apps/app1/tmp/pids/unicorn-master.pid

case "$1" in
  start)
 echo -n "Starting $DESC: "
 $DAEMON $DAEMON_OPTS
 echo "$NAME."
 ;;
  stop)
 echo -n "Stopping $DESC: "
        kill -QUIT `cat $PID`
 echo "$NAME."
 ;;
  restart)
 echo -n "Restarting $DESC: "
        kill -QUIT `cat $PID`
 sleep 1
 $DAEMON $DAEMON_OPTS
 echo "$NAME."
 ;;
  reload)
        echo -n "Reloading $DESC configuration: "
        kill -HUP `cat $PID`
        echo "$NAME."
        ;;
  *)
 echo "Usage: $NAME {start|stop|restart|reload}" >&2
 exit 1
 ;;
esac

exit 0

Then make sure to start it on start up.
$ sudo update-rc.d -f unicorn defaults
 Adding system startup for /etc/init.d/unicorn ...
   /etc/rc0.d/K20unicorn -> ../init.d/unicorn
   /etc/rc1.d/K20unicorn -> ../init.d/unicorn
   /etc/rc6.d/K20unicorn -> ../init.d/unicorn
   /etc/rc2.d/S20unicorn -> ../init.d/unicorn
   /etc/rc3.d/S20unicorn -> ../init.d/unicorn
   /etc/rc4.d/S20unicorn -> ../init.d/unicorn
   /etc/rc5.d/S20unicorn -> ../init.d/unicorn

7. Test

I rebooted the machine to check if Unicorn started automatically.
$ ps aux | grep unicorn
root      1151  0.6  0.2  14604 10900 ?        Sl   23:47   0:00 unicorn master -c /home/socrateos/public_html/apps/app1/unicorn.conf -E production -D                                    
root      1192  0.0  0.2  14604  9088 ?        Sl   23:47   0:00 unicorn worker[0] -c /home/socrateos/public_html/apps/app1/unicorn.conf -E production -D                                 
root      1195  0.0  0.2  14604  9088 ?        Sl   23:47   0:00 unicorn worker[1] -c /home/socrateos/public_html/apps/app1/unicorn.conf -E production -D                                 
root      1198  0.0  0.2  14604  9088 ?        Sl   23:47   0:00 unicorn worker[2] -c /home/socrateos/public_html/apps/app1/unicorn.conf -E production -D                                 
root      1201  0.0  0.2  14604  9092 ?        Sl   23:47   0:00 unicorn worker[3] -c /home/socrateos/public_html/apps/app1/unicorn.conf -E production -D                                 
1001      1820  0.0  0.0   5128   860 pts/0    S+   23:48   0:00 grep --color=auto unicorn
Yes!
Finally, go to http:\\www.domain3.com to see if I can see my Ramaze app.
The answer is YES.





Sunday, August 7, 2011

Setting up Private Virtual Hosts for Nginx on Ubuntu (11.04)

I am setting up private vitrual hosts for Nginx on my Ubuntu. I am following slicehost blog (see Resources section below).

1. Resources.
slicehost "Nginx Virtual Hosts #1"
slicehost "Nginx Virtual Hosts #2"

2. Build Directory Structure.
$ cd ~   # in my home directory
$ mkdir public_html
$ mkdir public_html/domain1.com  # first virtual host home directory
$ mkdir public_html/domain1.com/{public,private,log,backup} # and its sub-directoires
$ mkdir public_html/domain2.com  # second virtual host home directory
$ mkdir public_html/domain2.com/{public,private,log,backup} # and its sub-directories
It looks like this.






















3.Create Default Home Pages (index.html) for Each
$ gedit public_html/domain1.com/public/index.html
It's content is something like this:
<html>
  <head>
    <title>domain1.com</title>
  </head>
  <body>
    <h1>domain1.com</h1>
  </body>
</html>
Likewise,
$ gedit public_html/domain2.com/public/index.html
It's content is something like this:
<html>
  <head>
    <title>domain2.com</title>
  </head>
  <body>
    <h1>domain2.com</h1>
  </body>
</html>

4. Create vhost files.
$ sudo gedit /etc/nginx/sites-available/domain1.com
I copied and modified this from here at slicehost.
server {

            listen   80;
            server_name  www.domain1.com;
            rewrite ^/(.*) http://domain1.com/$1 permanent;

           }


server {

            listen   80;
            server_name domain1.com;

            access_log /home/socrateos/public_html/domain1.com/log/access.log;
            error_log /home/socrateos/public_html/domain1.com/log/error.log;

            location / {

                        root   /home/socrateos/public_html/domain1.com/public/;
                        index  index.html;

                        }

            }
The second one for domain2.com is similar.

5. Enable these vhosts.
By creating symlink files onto sites-enabled directory, the vhosts gets enabled.
$ sudo ln -s /etc/nginx/sites-available/domain1.com /etc/nginx/sites-enabled/domain1.com
$ sudo ln -s /etc/nginx/sites-available/domain2.com /etc/nginx/sites-enabled/domain2.com

6. Finally Edit Hosts file.
My tiny intranet does not use/need DNS. I will just manually update hosts files on few machines.
I added the following entries to /etc/hosts file on this (Ubuntu) machine (192.168.12.13).
127.0.1.1 domain1.com
127.0.1.1 www.domain1.com
127.0.1.1 domain2.com
127.0.1.1 www.domain2.com
I added similar entries to C:\Windows\System32\drivers\etc\hosts on my Windows Visita.
192.168.12.13 domain1.com
192.168.12.13 www.domain1.com
192.168.12.13 domain2.com
192.168.12.13 www.domain2.com
Type in "www.domain1.com" on my browser, and the result looks like below. However, it did not display correctly at first: it kept displaying the (Nginx) default index.html until I finally deleted the symlink file default from the /etc/nginx/sites-enabled/. Also I had a little problem displaying domain2.com page from the Windows machine at frist: it ketp displaying a page from the internet where there is a real domain called "domain2.com". But after repeating refreshing and stopping and starting IE, it started to display my domain2.com which actually resides on my Ubuntu.

Note that it is important to remove any entry from the hosts files if you need to access an internet site with the same domain name.

Installing members

I installed members, a program that displays all users who belong to a specified group.

1. Install.
Go to Synaptic. Search and install members.

2. Test.
Display all users who belong to group admin.
$ members admin
socrateos
$ 
Currently, I am the only member of admin.

Saturday, August 6, 2011

Installing Ramaze on Ubuntu (11.04)

I installed Ramaze (a lightweight web frame work. "RailsLite") on my Ubuntu 11.04.

1. Resources.
Ramaze Home: http://ramaze.net/
My Previous Installation on Ubuntu: http://socrateos.blogspot.com/2011/03/installing-ramaze.html

2. Install.
$ sudo gem install ramaze
[sudo] password for socrateos: 
Successfully installed innate-2011.04
Successfully installed ramaze-2011.07.25
2 gems installed
Installing ri documentation for innate-2011.04...
Installing ri documentation for ramaze-2011.07.25...
Installing RDoc documentation for innate-2011.04...
Installing RDoc documentation for ramaze-2011.07.25...
                   
$ ramaze -v    # be sure to have /var/lib/gems/1.9.1/bin in your PATH
2011.07.25

$ irb
irb(main):001:0> require 'ramaze'
=> true
irb(main):002:0> 

3. Create a Ramaze app.
$ cd work/ruby/ramaze
$ ramaze create myapp
The application has been generated and saved in myapp
$ cd myapp
$ ls
app.rb  config.ru  controller  layout  model  public  spec  start.rb  view
$ ramaze start
[2011-08-06 07:51:42] INFO  WEBrick 1.3.1
[2011-08-06 07:51:42] INFO  ruby 1.9.2 (2010-08-18) [i686-linux]
[2011-08-06 07:51:42] INFO  WEBrick::HTTPServer#start: pid=6063 port=7000

4. The Result (with Webrick) at http://localhost:7000.




















5. Run it with Unicorn instead of Webrick. (See Unicorn Installation)
$ cd work/ruby/ramaze/myapp
$ unicorn
I, [2011-08-06T11:33:11.738433 #1976]  INFO -- : listening on addr=0.0.0.0:8080 fd=3
I, [2011-08-06T11:33:11.738779 #1976]  INFO -- : worker=0 spawning...
I, [2011-08-06T11:33:11.739553 #1976]  INFO -- : master process ready
I, [2011-08-06T11:33:11.740215 #1978]  INFO -- : worker=0 spawned pid=1978
I, [2011-08-06T11:33:11.740420 #1978]  INFO -- : Refreshing Gem list
I, [2011-08-06T11:33:12.628489 #1978]  INFO -- : worker=0 ready

6. The Result (with Unicorn) at http://localhost:8080.
Great. It just works!

Friday, August 5, 2011

Installing Unicorn on Ubuntu (11.04)

Installed Unicorn.

1. Resources.
Unicorn: http://unicorn.bogomips.org/
Sleekd: http://sleekd.com/general/configuring-nginx-and-unicorn/

2. Install Unicorn
$ sudo gem install unicorn
Building native extensions.  This could take a while...
Building native extensions.  This could take a while...
Building native extensions.  This could take a while...
Successfully installed rack-1.3.2
Successfully installed kgio-2.6.0
Successfully installed raindrops-0.7.0
Successfully installed unicorn-4.0.1
4 gems installed
Installing ri documentation for rack-1.3.2...
Installing ri documentation for kgio-2.6.0...
Installing ri documentation for raindrops-0.7
.0...
Installing ri documentation for unicorn-4.0.1...
Installing RDoc documentation for rack-1.3.2...
Installing RDoc documentation for kgio-2.6.0...
Installing RDoc documentation for raindrops-0.7.0...
Installing RDoc documentation for unicorn-4.0.1...

3. Check Installation
$ irb
irb(main):001:0> require "unicorn"
=> true
irb(main):002:0>

4. Test Run a Rack App (Ramaze)
$ cd work/ruby/ramaze/myapp          # my ramaze app
$ unicorn
I, [2011-08-06T11:33:11.738433 #1976]  INFO -- : listening on addr=0.0.0.0:8080 fd=3
I, [2011-08-06T11:33:11.738779 #1976]  INFO -- : worker=0 spawning...
I, [2011-08-06T11:33:11.739553 #1976]  INFO -- : master process ready
I, [2011-08-06T11:33:11.740215 #1978]  INFO -- : worker=0 spawned pid=1978
I, [2011-08-06T11:33:11.740420 #1978]  INFO -- : Refreshing Gem list
I, [2011-08-06T11:33:12.628489 #1978]  INFO -- : worker=0 ready

5. The Result at http://localhost:8080.

Installing Nginx on Ubuntu (11.04)

I installed nginx on my Ubuntu (11.04), using Synaptic.

1. Resouces.
Nginx: http://wiki.nginx.org/
Sleekd: http://sleekd.com/general/configuring-nginx-and-unicorn/
Slicehost: http://articles.slicehost.com/nginx

2. Installation.
Search for nginx in Synaptic and install it.
It installs 3 packages, nginx, nginx-common, nginx-full.

3. Start the Nginx HTTP Server.
$ sudo /etc/init.d/nginx start      # start server
Starting nginx: nginx.
$ sudo /etc/init.d/nginx status     # check status
 * nginx is running

4. Test
http://localhost    # browser url
And the result is:













5. Check Installation

(1) Check the running processes.
$ ps aux | grep nginx
root      1253  0.0  0.0  10128   908 ?        Ss   19:43   0:00 nginx: master process /usr/sbin/nginx
www-data  1254  0.0  0.0  10280  1272 ?        S    19:43   0:00 nginx: worker process 
www-data  1255  0.0  0.0  10280  1272 ?        S    19:43   0:00 nginx: worker process
www-data  1257  0.0  0.0  10280  1272 ?        S    19:43   0:00 nginx: worker process
www-data  1258  0.0  0.0  10280  1272 ?        S    19:43   0:00 nginx: worker process
1001      2879  0.0  0.0   5128   856 pts/0    S+   21:52   0:00 grep --color=auto nginx
It looks like the installer created a new user www-data.

(2) Let's check this user.
$ finger www-data
Login: www-data          Name: www-data
Directory: /var/www      Shell: /bin/sh
Never logged in.
No mail.
No Plan.
It turned out that "the default web server user on Debian based systems is www-data" according to this site: slicehost. The installer also created a new group www-data, to which the user www-data belongs.
$ members www-data      # list all users who belong to group www-data.
www-data


(3) Get some more information about this installation with -V option.
$ nginx -V
nginx version: nginx/0.8.54
TLS SNI support enabled
configure arguments:
 --conf-path=/etc/nginx/nginx.conf                  # <==== Here is the path to nginx.conf.
 --error-log-path=/var/log/nginx/error.log
 --http-client-body-temp-path=/var/lib/nginx/body
 --http-fastcgi-temp-path=/var/lib/nginx/fastcgi
 --http-log-path=/var/log/nginx/access.log
 --http-proxy-temp-path=/var/lib/nginx/proxy
 --http-scgi-temp-path=/var/lib/nginx/scgi
 --http-uwsgi-temp-path=/var/lib/nginx/uwsgi
 --lock-path=/var/lock/nginx.lock
 --pid-path=/var/run/nginx.pid
 --with-debug
 --with-http_addition_module
 --with-http_dav_module
 --with-http_geoip_module
 --with-http_gzip_static_module
 --with-http_image_filter_module
 --with-http_realip_module
 --with-http_stub_status_module>
 --with-http_ssl_module
 --with-http_sub_module
 --with-http_xslt_module
 --with-ipv6
 --with-sha1=/usr/include/openssl
 --with-md5=/usr/include/openssl
 --with-mail
 --with-mail_ssl_module
 --add-module=/build/buildd/nginx-0.8.54/debian/modules/nginx-upstream-fair

6. Configuration Files.
Let's look at some configuration files.

(1) /etc/nginx/nginx.conf
user www-data;
worker_processes 4;
pid /var/run/nginx.pid;

events {
 worker_connections 768;
 # multi_accept on;
}

http {

 ##
 # Basic Settings
 ##

 sendfile on;
 tcp_nopush on;
 tcp_nodelay on;
 keepalive_timeout 65;
 types_hash_max_size 2048;
 # server_tokens off;

 # server_names_hash_bucket_size 64;
 # server_name_in_redirect off;

 include /etc/nginx/mime.types;
 default_type application/octet-stream;

 ##
 # Logging Settings
 ##

 access_log /var/log/nginx/access.log;
 error_log /var/log/nginx/error.log;

 ##
 # Gzip Settings
 ##

 gzip on;
 gzip_disable "msie6";

 # gzip_vary on;
 # gzip_proxied any;
 # gzip_comp_level 6;
 # gzip_buffers 16 8k;
 # gzip_http_version 1.1;
 # gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

 ##
 # Virtual Host Configs
 ##

 include /etc/nginx/conf.d/*.conf;
 include /etc/nginx/sites-enabled/*;
}


#mail {
# # See sample authentication script at:
# # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
# 
# # auth_http localhost/auth.php;
# # pop3_capabilities "TOP" "USER";
# # imap_capabilities "IMAP4rev1" "UIDPLUS";
# 
# server {
#  listen     localhost:110;
#  protocol   pop3;
#  proxy      on;
# }
# 
# server {
#  listen     localhost:143;
#  protocol   imap;
#  proxy      on;
# }
#}

(2) /etc/nginx/sites-available/default

# You may add here your
# server {
# ...
# }
# statements for each of your virtual hosts to this file

##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# http://wiki.nginx.org/Pitfalls
# http://wiki.nginx.org/QuickStart
# http://wiki.nginx.org/Configuration
#
# Generally, you will want to move this file somewhere, and start with a clean
# file but keep this around for reference. Or just disable in sites-enabled.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

server {
 #listen   80; ## listen for ipv4; this line is default and implied
 #listen   [::]:80 default ipv6only=on; ## listen for ipv6

 root /usr/share/nginx/www;
 index index.html index.htm;

 # Make site accessible from http://localhost/
 server_name localhost;

 location / {
  # First attempt to serve request as file, then
  # as directory, then fall back to index.html
  try_files $uri $uri/ /index.html;
 }

 location /doc {
  root /usr/share;
  autoindex on;
  allow 127.0.0.1;
  deny all;
 }

 location /images {
  root /usr/share;
  autoindex off;
 }

 #error_page 404 /404.html;

 # redirect server error pages to the static page /50x.html
 #
 #error_page 500 502 503 504 /50x.html;
 #location = /50x.html {
 # root /usr/share/nginx/www;
 #}

 # proxy the PHP scripts to Apache listening on 127.0.0.1:80
 #
 #location ~ \.php$ {
 # proxy_pass http://127.0.0.1;
 #}

 # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
 #
 #location ~ \.php$ {
 # fastcgi_pass 127.0.0.1:9000;
 # fastcgi_index index.php;
 # include fastcgi_params;
 #}

 # deny access to .htaccess files, if Apache's document root
 # concurs with nginx's one
 #
 #location ~ /\.ht {
 # deny all;
 #}
}


# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# root html;
# index index.html index.htm;
#
# location / {
#  try_files $uri $uri/ /index.html;
# }
#}


# HTTPS server
#
#server {
# listen 443;
# server_name localhost;
#
# root html;
# index index.html index.htm;
#
# ssl on;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
#
# ssl_session_timeout 5m;
#
# ssl_protocols SSLv3 TLSv1;
# ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv3:+EXP;
# ssl_prefer_server_ciphers on;
#
# location / {
#  try_files $uri $uri/ /index.html;
# }
#}

OK, according to this conf file, the root directory for the default site is /usr/share/nginx/www.
And its home page file is index.html. Let's make some change.
$ cd /usr/share/nginx/www
$ ls
50x.html  index.html
$ sudo gedit index.html
I made a change to the welcome text from "Welcome to nginx!" to "Welcome to My Nginx!" with blue color.
And here is the result.