Friday, April 28, 2017

Creating a clickable image in Ruby on Rails

It is still my beginning stage to learn Ruby on Rails. I found that is quite challenging to create a clickable image in html.erb (Ruby Embedded HTML). A clickable image can be created easily by the <a href><img></a> pattern in plain HTML5.

For example, a very common pattern in plain HTML:
<a href="img/img-21-01.jpg">
  <img src="img/img-21-01.jpg" alt="Image" class="img-fluid tm-header-img">    
</a>
This pattern can create an image that can be clicked and enlarged.

After I searched Google, read some articles in StackOverflow and Michael Hartl's Tutorial book. I conclude a simplier <%= link_to image_tag %> pattern to create a clickable image:

<%= link_to image_tag("picture01.jpg", alt: "Image Description"), image_path("picture01.jpg") %>

Again, in plain HTML:
<a href="img/img-21-01.jpg">
  <img src="img/img-21-01.jpg" alt="Image" class="img-fluid tm-header-img">    
</a>

I re-wrote into html.erb:
<%= link_to image_tag("img-21-01.jpg", :alt => "Image", :class => "img-fluid tm-header-img" ), image_path("img-21-01.jpg") %>

This is a simplified pattern to create a clickable image in html.erb (Ruby Embedded HTML).

The images in the home page:

Click the image to enlarge it:


References:
ruby on rails link_to an image
http://stackoverflow.com/questions/18484543/ruby-on-rails-link-to-an-image

image_path (ActionView::Helpers::AssetTagHelper) - APIdock
https://apidock.com/rails/ActionView/Helpers/AssetTagHelper/image_path

5.1.1 Site navigation
https://www.railstutorial.org/book/filling_in_the_layout#sec-adding_to_the_layout

Experiment: Cloning a CSS template to Ruby on Rails using the static pages feature

After I have read the chapter 3 of Michael Hartl's book to generate static pages using Ruby on Rails static pages generator. I wanted to try to find some CSS templates, downloaded the CSS templates to my hard drive and hosted them on my Ruby on Rails server.

* First, I searched Google: "free css templates"

* Let's say, I liked the style of this CSS templates http://www.templatemo.com/live/templatemo_495_metro_fit  and downloaded it to my hard drive.

* I unzipped the CSS templates in my ~/html folder

* I tried the CSS template by opening the index.html file on my local drive using Firefox:
file:///home/jimmyc/html/templatemo_495_metro_fit/index.html

* To host a CSS template on my Ruby on Rails server, I created a new Rails project called "static1":
$ cd ~
$ rails new static1
$ cd static1
$ bundle install

* I initialized the Git repository:
$ git init
$ git add -A
$ git commit -m "Init"

* I updated the README.md file
# Hosting a CSS template using Rails static page feature
This is the CSS template from http://www.templatemo.com/live/templatemo_495_metro_fit

## Getting started
To get started, clone this repository and then install the needed gems:
```
$ git clone
```

Next, run bundle install:
```
$ bundle install
```

Migrate the database:
```
$ rails db:migrate
```

Start the server:
```
$ rails s -b 0.0.0.0 -p 3000
```

Navigate the website, in a browser:
```
http://localhost:3000/
```
* I committed the changes:
$ git commit -am "Updated README"

* I created a new Github repository called static1 and I pushed it onto Github:
$ git remote add origin https://github.com/jimmy2046/static1.git
$ git push -u origin master
* I created a branch static-pages:

git checkout -b static-pages

* Now, this is important: I created static pages controller for pages Home and About:
$ rails generate controller StaticPages home about

* I pushed the static pages controller to Github:
$ git add -A
$ git commit -m "Add a Static Pages controller"
$ git push -u origin static-pages

* I set the root location for config/routes.rb:
 Rails.application.routes.draw do
  get 'static_pages/home'
  get 'static_pages/about'
  root 'static_pages#home'  
end
* I started the Rails server:
$ rails s -b 0.0.0.0 -p 3000

* I tested to navigate to the homepage:

* I checked the test/controllers/static_pages_controller_test.rb file:
require 'test_helper'

class StaticPagesControllerTest < ActionDispatch::IntegrationTest
  test "should get home" do
    get static_pages_home_url
    assert_response :success
  end

  test "should get about" do
    get static_pages_about_url
    assert_response :success
  end

end

* I ran the test:
$ rails test
2 runs, 2 assertions, 0 failures, 0 errors, 0 skips

* The second important procedure is to copy the CSS files, images file to the Rails project.

* I copied all CSS files from the template to path: app/assets/stylesheets/ of my rails project static1:
$ cp ~/html/templatemo_495_metro_fit/css/* ~/static1/app/assets/stylesheets/

* I copied all images files from the template to my rails project:
$ cp ~/html/templatemo_495_metro_fit/img/* ~/static1/app/assets/images/

* I copied all Javascript files:
$ cp ~/html/templatemo_495_metro_fit/js/* ~/static1/app/assets/javascripts/

* I renamed the original home.html.erb file and copy the index.html file from the template to my Rails project:
$ mv ~/static1/app/views/static_pages/home.html.erb home_original.html.erb
$ cp ~/html/templatemo_495_metro_fit/index.html ~/static1/app/views/static_pages/home.html.erb

* I renamed the original about.html.erb file and copy the about.html file:
$ mv ~/static1/app/views/static_pages/about.html.erb about_original.html.erb
$ cp ~/html/templatemo_495_metro_fit/about.html ~/static1/app/views/static_pages/about.html.erb

* After I had copied the theme files from the template, I ran the test again:
$ rails test
2 runs, 2 assertions, 0 failures, 0 errors, 0 skips

* Using Brackets, I edited the ~/static1/app/views/static_pages/home.html.erb file

* In home.html.erb file:
  • Replace all href="css/ to href="/assets/css/ in the file.

* I did in the same with about.html.erb file:
Replace all href="css/ to href="/assets/css/ in the file.

* There is no "replace all" method to display all the image files (such as JPG, PNG and GIF files). My way for displaying all image in Ruby Embedded HTML html.erb is to replace all <img> tags with <%=  image_tag %>:
  • For example, I changed these <img> tags  from html:
<a href="img/img-21-01.jpg">
  <img src="img/img-21-01.jpg" alt="Image" class="img-fluid tm-header-img">   
</a>
  • To this codes to fit html.erb:
<%= image_tag("img-21-01.jpg", :alt => "Image", :class => "img-fluid tm-header-img") %>

* For the icons those contain "bicycle", "camera", and "street view", I did not understand what does the HTML i tag and class="fa fa-4x fa-bicycle tm-content-icon" mean. Perhaps the special fonts in Font Awesome. I just capture the screen (alt + PrtScn), saved it as a JPG file (bicycle.jpg) and use the Ruby image_tag function to show it on the screen. This is a simple "short cut" to make it works.
  • For the bicycle icon, I re-wrote:
<i class="fa fa-4x fa-bicycle tm-content-icon"></i>
  • To
<div class="fa fa-4x fa-bicycle tm-content-icon">
  <%= image_tag("bicycle.jpg") %>
</div>

* For the Font Awesome on the bottom such as Facebook, Twitter fonts:
  • For example, for the Linkedin Font Awesome,  I re-wrote:
<a href="#" class="tm-social-link"><i class="fa fa-linkedin"></i></a>
  • To:
<%= image_tag("linkedin_icon.jpg") %>

* I had re-written all image_tag on the home.html.erb page. At this milestone, I added all untracked files, I committed the changes and pushed it onto Github:
$ git add -A
$ git commit -m "Re-written image_tag 2"
$ git checkout master
$ git merge static-pages
$ git push

* I checked my changes by viewing: https://github.com/jimmy2046/static1/blob/master/app/views/static_pages/home.html.erb

* After I had re-written all the image tags, I was going to re-write the link_to tag.

* In the routing file: config/rotues.rb
  • I re-wrote:
get 'static_pages/about'
  • To:
get  '/about',   to: 'static_pages#about'

 * It is optional to re-write <a href> tag to <%= link_to %> tag. To re-write the links, I re-wrote <a href> tag in the Home file:
app/views/static_pages/home.html.erb
  • For example, for the About page link, I changed:
<a class="nav-link" href="about.html">About</a>
  •  To:
<div class="nav-link">
   <%= link_to "About", about_path %>
</div>

* Similarly, I edited the routing path for home.html.erb
config/routes.rb
get '/home', to: 'static_pages#home'

* And I changed the link_to tags in home.html.erb and about.html.erb
For example, in app/views/static_pages/home.html.erb
  • I changed:
<a class="nav-link" href="#">Home</a>
  • To:
<div class="nav-link"><% link_to "Home", home_path %></div>

* I changed the link_to tags in about.html.erb as well.

* After I have made the changes of image_tag and link_to tags for home.html.erb and about.html.erb and I have changed the routes.rb file. I needed to prepare the the test suite for the web site.

* It is because I had changed the routes.rb file, I have to change the path in the test cases for static pages controller:
For example in test/controllers/static_pages_controller_test.r
  • I changed
 get static_pages_home_url
  • To
 get home_path

* Then, I ran the test to ensure the Home and About page can be routed:
$ rails test
2 runs, 2 assertions, 0 failures, 0 errors, 0 skips

* I wrote 2 test cases for checking the title is display correctly in Home and About pages.
require 'test_helper'

class StaticPagesControllerTest < ActionDispatch::IntegrationTest
  test "should get home" do
      get home_path
    assert_response :success
    assert_select "title", "Home"     
  end

  test "should get about" do
      get about_path
    assert_response :success
    assert_select "title", "About"
  end

end
* It is because the default title is the name of the project "static1", the test would fail for incorrect title.
$ rails test
Failure:
StaticPagesControllerTest#test_should_get_about [/home/jimmyc/static1/test/controllers/static_pages_controller_test.rb:13]:
<About> expected but was
<Static1>..
Expected 0 to be >= 1.

* To change the title of the pages, the the Application Layout file:
Located:  app/views/layouts/application.html.erb
  • I changed
<title>Static1</title>
  • To
<title><%= yield(:title) %></title>

* Afterwards,
in app/views/static_pages/home.html.erb
I added 2 lines in home.html.erb.
  • On the top:
<% provide(:title, "Home") %>
  • and I changed the <title> tag:
<title><%= yield(:title) %></title>

* Similarly, for app/views/static_pages/about.html.erb
 <% provide(:title, "About") %>
...
<title><%= yield(:title) %></title>

* After I had corrected the title, the test passes:
$ rails test
2 runs, 4 assertions, 0 failures, 0 errors, 0 skips

* After the completion of Home and About, I wanted to add a Services page.

* I copied the services.html file from the template to app/views/static_pages and renamed it as services.html.erb

* I wrote a test case for Service page.
test/controllers/static_pages_controller_test.rb
test "should get services" do
  get services_path
  assert_response :success
  assert_select "title", "Services"
end

* I updated the routes.rb file for Services page:
config/routes.rb
Rails.application.routes.draw do
# home_path
  get '/home',     to: 'static_pages#home'
# about_path   
  get '/about',    to: 'static_pages#about'   
# services_path
  get '/services', to: 'static_pages#services'   
  root 'static_pages#home'   
end

* I added services method in the static pages controller:
app/controllers/static_pages_controller.rb
class StaticPagesController < ApplicationController
  def home
  end

  def about
  end
   
  def services
  end
   
end

* I changed the <title> of Services page:
app/views/static_pages/services.html.erb
<% provide(:title, "Services") %>
...
<title><%= yield(:title) %></title>

* After the above steps, the test is supposed to pass:
$ rails test
3 runs, 6 assertions, 0 failures, 0 errors, 0 skips

* And then, in the services.html.erb, I did the similar things for changing the image_tag and link_to methods in the file.

* Afterwards, I did above steps recursively to add 'Blog' page and 'Contact' page.
 
* After I had re-written all <%= image_tag %> tags in all pages. I ran the sanitary test to ensure all path and page <title> are correct.
test/controllers/static_pages_controller_test.rb
require 'test_helper'

class StaticPagesControllerTest < ActionDispatch::IntegrationTest
  test "should get home" do
      get home_path
    assert_response :success
    assert_select "title", "Home"     
  end

  test "should get about" do
      get about_path
    assert_response :success
    assert_select "title", "About"
  end
   
  test "should get services" do
    get services_path
    assert_response :success
    assert_select "title", "Services"
  end
   
  test "should get blog" do
    get blog_path
    assert_response :success
    assert_select "title", "Blog"
  end
   
  test "should get contact" do
    get contact_path
    assert_response :success
    assert_select "title", "Contact"
  end
     
end

* The command line to run the test:
$ rails test
Finished in 0.580862s, 8.6079 runs/s, 17.2158 assertions/s.
5 runs, 10 assertions, 0 failures, 0 errors, 0 skips

* Finally, I added all untracked files, committed it and pushed it onto Github:
$ git add -A
$ git commit -am "all pages"
$ git push

* You can view my result pages on:
https://github.com/jimmy2046/static1

* You can clone (download) to your local hard drive by:
$ git clone https://github.com/jimmy2046/static1.git

Thursday, April 27, 2017

I learned the basics of Ruby language

Today, I finished up the chapter 4 of the book: Rails-flavored Ruby https://www.railstutorial.org/book/rails_flavored_ruby#cha-rails_flavored_ruby.

In refer to the instructions from the book:

* I created a separate topic branch "rails-flavored-ruby"
$ git checkout -b rails-flavored-ruby


 * I defined a custom helper called full_title, to solve the problem of a missing page title.
app/helpers/application_helper.rb
module ApplicationHelper

  # Returns the full title on a per-page basis.
  def full_title(page_title = '')
    base_title = "Ruby on Rails Tutorial Sample App"
    if page_title.empty?
      base_title
    else
      page_title + " | " + base_title
    end
  end
end

* I simplified my application layout
app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
  <head>
    <title><%= full_title(yield(:title)) %></title>
      <%= csrf_meta_tags %>
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
    <%= yield %>
  </body>
</html>

* I eliminated the code repeatation in Home, About and Contact for the test cases in the static pages controller:
test/controllers/static_pages_controller_test.rb
require 'test_helper'

class StaticPagesControllerTest < ActionDispatch::IntegrationTest

  def setup
    @base_title = "Ruby on Rails Tutorial Sample App"
  end
   
  test "should get root" do
    get root_url
    assert_response :success
  end
   
    test "should get home" do
    get static_pages_home_url
    assert_response :success
    assert_select "title", "Ruby on Rails Tutorial Sample App"       
    end

  test "should get help" do
    get static_pages_help_url
    assert_response :success
    assert_select "title", "Help | #{@base_title}"
  end

  test "should get about" do
    get static_pages_about_url
    assert_response :success
    assert_select "title", "About | #{@base_title}"
  end
   
  test "should get contact" do
      get static_pages_contact_url
      assert_response :success
      assert_select "title", "Contact | #{@base_title}"
  end   
   
end

* And then, I read the introduction of Ruby programming language including methods, objects, class, def keyword, class keyword, HTML embedded Ruby ERB, data structures include arrays, ranges, hashes, inheritances, superclass, and etc. I did not do the Ruby programming exercises.

* After that, I commited the changes, and I merged the rails-flavoured-ruby branch to master:
$ git commit -am "Add a full_title helper"
$ git checkout master
$ git merge rails-flavored-ruby

* I did a sanity check before push:
$ rails test
5 runs, 9 assertions, 0 failures, 0 errors, 0 skips

* I pushed it up to Github - https://github.com/jimmy2046/sample_app:
$ git push

Sunday, April 23, 2017

The making of static pages using Ruby on Rails

Today, I finished the chapter 3 of Michael Hartl's Ruby on Rails book. I did everything up to 3.5: Conclusion. I did not do the optional Advance Testing Setup after 3.6.

The online version of chapter 3:
https://www.railstutorial.org/book/static_pages#cha-static_pages

My Github repository:
https://github.com/jimmy2046/sample_app

* First, I created a new Rails project called sample_app:
$ rails _5.0.1_ new sample_app

* I did not changed the Gemfile and this is my Gemfile
source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end


# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.1'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '~> 3.0.5'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

* I installed the Gemfile without production part:
$ bundle install --without production
$ bundle update

* I initialized a Git repository:
$ git init
$ git add -A
$ git commit -m "Initialize repository"

* I updated the README.md file, committed the changes, and pushed it onto Github:
$ git commit -am "Improve the README"
$ git remote add origin https://github.com/jimmy2046/sample_app.git
$ git push -u origin --all # pushes up the repo and its refs for the first time
* I tested the new project by Hello World in the Application controller (app/controllers/application_controller.rb):

 class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  
  def hello
    render html: "hello, world!"
  end  
end
* The config/routes.rb specifies what pages are going to send out in according to visitor's HTTP GET request:
Rails.application.routes.draw do
  root 'static_pages#home'
   
  get 'static_pages/home'
  get 'static_pages/help'
  get 'static_pages/about'
  get 'static_pages/contact'
end

*  I committed the changes for edited application_controller.rb and routes.rb:
$ git commit -am "Add hello"
$ git push

* I check out a branch for creating static pages:
$ git checkout -b static-pages

* I generated a Static Pages controller for home.html.erb and help.html.erb:
$ rails generate controller StaticPages home help

* I committed the changes for the creation of Static Pages controller and pushed it to Git hub:
$ git add -A
$ git commit -m "Add a Static Pages controller"
$ git push -u origin static-pages
$ git push

* I added the routes for home.html.erb and help.html.erb:
Rails.application.routes.draw do
  root 'static_pages#home'
   
  get 'static_pages/home'
  get 'static_pages/help'
  get 'static_pages/about'
  get 'static_pages/contact'
end

* I started the Rails server:
$ rails s -b 0.0.0.0 -p 3000

* I navigated it using Firefox:
http://localhost:3000/static_pages/home

* The Rails Generate command created the app/controllers/static_pages_controller.rb file automatically. The generate command also added the def home and def help methods in the Ruby controller file. I added def about and def contact methods in according to the instruction of the book.
class StaticPagesController < ApplicationController
  def home
  end

  def help
  end
   
  def about
  end
   
  def contact
  end
   
end

* The controller also created 2 new files: home.html.erb and help.html.erb. The <% > part is where the Ruby program command to be run.  In the first line it returns a value "Home" to the variable  "title":
<% provide(:title, "Home") %>
<h1>Sample App</h1>
<p>
  This is the home page for the
  <a href="http://www.railstutorial.org/">Ruby on Rails Tutorial</a>
  sample application.
</p>

* Similarly, this is the app/views/static_pages/help.html.erb file:

<% provide(:title, "Help") %>
<h1>Help</h1>
<p>
  Get help on the Ruby on Rails Tutorial at the
  <a href="http://www.railstutorial.org/help">Rails Tutorial help section</a>.
  To get help on this sample app, see the
  <a href="http://www.railstutorial.org/book"><em>Ruby on Rails Tutorial</em>
  book</a>.
</p>

* The Ruby on Rails framework is designed to be test-driven development (TDD) ready. It is a testing technique in which the programmer writes failing tests first, and then writes the application code to get the tests to pass. The testing codes are written in advanced the Ruby codes and HTML pages.

* The test/controllers/static_pages_controller_test.rb specifies the testing rules for the static pages controllers: 
require 'test_helper'

class StaticPagesControllerTest < ActionDispatch::IntegrationTest

  def setup
    @base_title = "Ruby on Rails Tutorial Sample App"
  end
   
  test "should get root" do
    get root_url
    assert_response :success
  end
   
    test "should get home" do
    get static_pages_home_url
    assert_response :success
    assert_select "title", "Home | #{@base_title}"
    end

  test "should get help" do
    get static_pages_help_url
    assert_response :success
    assert_select "title", "Help | #{@base_title}"
  end

  test "should get about" do
    get static_pages_about_url
    assert_response :success
    assert_select "title", "About | #{@base_title}"
  end
   
  test "should get contact" do
      get static_pages_contact_url
      assert_response :success
      assert_select "title", "Contact | #{@base_title}"
  end   
   
end

* To run a test, use the rails test command:
$ rails test

* If a wanted to add a new static page called: about.html.erb
1. I added a new test case in test/controllers/static_pages_controller_test.rb
  test "should get about" do
    get static_pages_about_url
    assert_response :success
  end

2. I added a new routing location in config/routes.rb:
get 'static_pages/about'

3. I defined a new module in  app/controllers/static_pages_controller.rb:
  def about
  end
 4. I created a new Ruby Embedded HTML file app/views/static_pages/about.html.erb. One method is using the Linux touch command:

$ touch app/views/static_pages/about.html.erb
 5. I wrote the about.html.erb:
<h1>About</h1>
<p>
  The <a href="http://www.railstutorial.org/"><em>Ruby on Rails
  Tutorial</em></a> is a
  <a href="http://www.railstutorial.org/book">book</a> and
  <a href="http://screencasts.railstutorial.org/">screencast series</a>
  to teach web development with
  <a href="http://rubyonrails.org/">Ruby on Rails</a>.
  This is the sample application for the tutorial.
</p>
6. I ran the test:
$ rails test

* I also did the 3.4 Slightly Dynamic Pages part. But I do not want to explain it in details. For details, please refer to: https://www.railstutorial.org/book/static_pages#sec-slightly_dynamic_pages

* When I finished, I committed it and pushed it onto Github:
$ git add -A
$ git commit -m "Finish static pages"
$ git checkout master
$ git merge static-pages
$ git push

* You can find it on:

Pinta image editor for Ubuntu Linux

Microsoft Windows Paint enables the basic image editing functionality. In Ubuntu Linux, there is a Pinta program offers the similar image editing features like Microsoft Paint. It does not equipped with Ubuntu installation and it needs to be installed by Ubuntu Software installation program.

To install Pinta in Ubuntu Linux:

1. Click Ubuntu Software:

2.  In Ubuntu software:
  • Click all
  • Search "pinta"
  • Click install 

3. Pinta is installed on the menu bar on the left hand side. To start Pinta, you may click the Pinta icon or type "pinta" in Linux shell terminal.


Reference:
Is there a program like Microsoft Paint? [duplicate]
https://askubuntu.com/questions/36577/is-there-a-program-like-microsoft-paint

Apply a CSS template to my Rails project

The tutorial in Getting Started with Rails clearly explains the procedures to build the "skeletons" of a blog web application that can read, add, edit and delete a blog post. It does not come with the style and formatting of the web page design. Today, I was trying to search a CSS template and apply it to my Rails project.

1. I searched Google: "css blog template":

2. I selected this CSS template (http://www.free-css.com/free-css-templates/page207/saturn) and downloaded to my local hard drive:

3. I created a new directory html and I unzipped the downloaded file to the new directory:
mkdir ~/html
cp ~/Downloads/Saturn Free Website Template - Free-CSS.com.zip ~/html
cd ~/html
unzip Saturn Free Website Template - Free-CSS.com.zip -d

4. Copy all the CSS files from the template to app/assets/stylesheets directory:
cp ~/html/Saturn HTML Template/css ~/gettingstarttedwithrails/app/assets/stylesheets

5. Copy all the image files from the template to app/assets/images directory:
cp ~/html/Saturn HTML Template/img ~/gettingstarttedwithrails/app/assets/images

6. I did my experiment first on the welcome view. I renamed the index.html.erb file. Then, I copied the index.html file from the template to my Ruby on Rails project:
mv ~/gettingstarttedwithrails/app/views/welcome/index.html.erb index_original.html.erb
cp ~/html/Saturn HTML Template/index.html ~/gettingstarttedwithrails/app/views/welcome/index.html.erb

7. I edited the app/views/welcome/index.html.erb using the Brackets editor. I changed the path of all CSS files to /assets/css/:
<head>
...
   <link rel="stylesheet" href="/assets/css/kube.min.css" />
   <link rel="stylesheet" href="/assets/css/font-awesome.min.css" />
   <link rel="stylesheet" href="/assets/css/custom.min.css" />
...
</head>
8. Finally, I still needed to do some "fine tuning" to the index.html.erb file to make the web template to fit the purpose of of my blog.

This is what I called the "fast track" method to "copy and paste" a web template to my Ruby on Rails project. Although I still need to do many codings in HTML, the appearance of the website is much more professional looking without spending a lot of time to start from scratch. Another advantage is that I can quickly changed the theme of my Rails project by downloading another CSS template to my Rails server. By the way, I found that the background image in the CSS file will be overrided (re-written) by the Rails framework. I am finding some "work around" to overcome the background image "white-out" problem.

Saturday, April 22, 2017

Brackets HTML and CSS editor for Ubuntu Linux

Ubuntu Linux comes with the gedit editor, which is very handy for writing and editing Ruby programs as well as HTML pages. But if I want to make a more professional looking and fancy web pages using HTML and CSS, I will need a more powerful HTML editor. In Windows, there is the professional grade Adobe Dreamweaver program for designing professional look web pages. In Linux, I found the Brackets open source software, which provides basic HTML and CSS files editing. It is developed by Adobe and distributed under the MIT license. All and all, it is free.

1. To install Brackets for Linux, I typed the following command in Terminal:
$ sudo add-apt-repository ppa:webupd8team/brackets
$ sudo apt-get update
$ sudo apt-get install brackets
2. And then the installation process is very straight forward, quick and easy. To start Brackets, I typed brackets in Linux Terminal:
$ brackets
3. It will start Brackets and goes straight into an HTML-based tutorial file with accompanying CSS, which is a great way to start exploring.


4. Finally, I right clicked the Brackets icon on the toolbar on the left and locked it with the Launcher for easy access.

Note: the Brackets software is installed on:
/opt/brackets

and the sample index.html and main.css files are located on:
/opt/brackets/samples/root/Getting Started


Reference:
What is the best editor for HTML, CSS etc? [duplicate]
https://askubuntu.com/questions/585960/what-is-the-best-editor-for-html-css-etc

A Review of the Brackets Editor
https://www.sitepoint.com/review-brackets-editor/

Brackets - A modern, open source code editor that understands web design.
http://brackets.io/

Brackets (text editor)
https://en.wikipedia.org/wiki/Brackets_(text_editor)

GETTING STARTED WITH BRACKETS
file:///opt/brackets/samples/root/Getting%20Started/index.html

The trick to start Rails server

Today, I have got a simple and practical method to start my Rails server in order to make it work properly. If I want to start Rails server, I have to type this in Linux Terminal:
$ rails s -b 0.0.0.0 -p 3000

I did not know this until today I wanted to connect to Rails server remotely using my MacBook Air.

1. At the beginning, I started Rails server using my old method:
$ rails s

=> Booting Puma
=> Rails 5.0.2 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.8.2 (ruby 2.4.0-p0), codename: Sassy Salamander
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://localhost:3000
Use Ctrl-C to stop

2. I could navigate to the Rails server locally using the Firefox connection localhost port 3000 from my Dell desktop which is hosting the Rails server:


3. But I could not navigate to Rails server remotely using the Firefox in my MacBook Air.


 
4. Afterwards, I did some research using Google search and read some articles in stackoverflow.com and serverfault.com. To sum up, I have to start the Rails server by:
$ rails s -b 0.0.0.0 -p 3000
instead of
$ rails s

5. The next step, I stopped the Rails server by pressing Ctrl + C. And then I typed: $ rails s -b 0.0.0.0 -p 3000:
$ rails s -b 0.0.0.0 -p 3000

=> Booting Puma
=> Rails 5.0.2 application starting in development on http://0.0.0.0:3000
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.8.2 (ruby 2.4.0-p0), codename: Sassy Salamander
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://0.0.0.0:3000
Use Ctrl-C to stop

6. This time, I can connect to Rails server remotely using Firefox from my MacBook Air.


In refer to the article from Stackoverflow, I am not fully understand what does the parameter -b 0.0.0.0 mean. But basically, if I start the Rails server without parameter, the Rails server only accept local connection. If I add the -b 0.0.0.0 parameter Rails is listening on all interfaces, not just the loopback interface.


References:
Can't access ports assigned to Rails 4.2, but 4.04 works fine
https://serverfault.com/questions/625841/cant-access-ports-assigned-to-rails-4-2-but-4-04-works-fine

Why does Ruby on Rails use http://0.0.0.0:3000 instead of http://localhost:3000?
http://stackoverflow.com/questions/1478747/why-does-ruby-on-rails-use-http-0-0-0-03000-instead-of-http-localhost3000

Friday, April 21, 2017

Rails Scaffold Generators

Today, I finished Michael Hartl's chapter 2: A toy app (https://www.railstutorial.org/book/toy_app#cha-a_toy_app) . This chapter provides an overview to create a rails project with large amount of functionality automatically using the scaffold generator.

1. First thing first, create a new rails project:
$ cd ~
$ rails _5.0.1_ new toy_app
$ cd toy_app/
$ bundle install --without production

2. Initialize Git:
$ git init
$ git add -A
$ git commit -m "Initialize repository"
$ git remote add origin https://github.com/jimmy2046/toy_app.git
$ git push -u origin master

3. The config/routes.rb file re-directs the visitor to specific URL location (http://localhost:3000/users) when the a user is going to (http://localhost:3000/):
Rails.application.routes.draw do
  resources :microposts
  resources :users
  root 'users#index'
end

4. Generate a user data model using the scaffold parameter. A user has a name (string) and an email (string):
$ rails generate scaffold User name:string email:string


5. Database migration is needed each time a data model is created or modified:
$ rails db:migrate

6. Start the Rails server:
$ rails server

7. Browse it by Firefox:

8. The web application allows users to:
  • Add a new user
  • Edit user information
  • Delete a user

9. The users_controller.rb file is sub-class of application_controller.rb file. It is generated automatically by the scaffold parameter. The program explains the details instruction in Ruby when a command received. These include listing all users, showing a user, adding a user, editing a user, and deleting a user:

class UsersController < ApplicationController
  before_action :set_user, only: [:show, :edit, :update, :destroy]

  # GET /users
  # GET /users.json
  def index
    @users = User.all
  end

  # GET /users/1
  # GET /users/1.json
  def show
  end

  # GET /users/new
  def new
    @user = User.new
  end

  # GET /users/1/edit
  def edit
  end

  # POST /users
  # POST /users.json
  def create
    @user = User.new(user_params)

    respond_to do |format|
      if @user.save
        format.html { redirect_to @user, notice: 'User was successfully created.' }
        format.json { render :show, status: :created, location: @user }
      else
        format.html { render :new }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /users/1
  # PATCH/PUT /users/1.json
  def update
    respond_to do |format|
      if @user.update(user_params)
        format.html { redirect_to @user, notice: 'User was successfully updated.' }
        format.json { render :show, status: :ok, location: @user }
      else
        format.html { render :edit }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /users/1
  # DELETE /users/1.json
  def destroy
    @user.destroy
    respond_to do |format|
      format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_user
      @user = User.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def user_params
      params.require(:user).permit(:name, :email)
    end
end



10. The User Model file user.rb specifies the meta data of table user in the database. As we can see in the codes, each user can have many microposts (foreign key). A user has a name and an email. The name and email are required fields that cannot be blank (not null).
class User < ApplicationRecord
  has_many :microposts
  validates :name, presence: true
  validates :email, presence: true
end

11. The app/views/users/index.html.erb file is a Ruby Embedded HTML file (ERB file). This presents the format of the HTML file when a visitor wants to see a list of users. This is a table with 2 columns. There are meta data: Name and Email. And there are text box for user input.
<h1>Listing users</h1>

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Email</th>
      <th colspan="3"></th>
    </tr>
  </thead>

<% @users.each do |user| %>
  <tr>
    <td><%= user.name %></td>
    <td><%= user.email %></td>
    <td><%= link_to 'Show', user %></td>
    <td><%= link_to 'Edit', edit_user_path(user) %></td>
    <td><%= link_to 'Destroy', user, method: :delete,
                                     data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>
</table>

<br>

<%= link_to 'New User', new_user_path %>

12. Now, creating a second database table Micropost with meta data content (text) and user_id (integer):
$ rails generate scaffold Micropost content:text user_id:integer

13. Again, don't forget to do database migration:
$ rails db:migrate

14. The micropost controller: app/controllers/microposts_controller.rb is very similar to user controller. It defines the database actions, such as list, show, new, edit, destroy and etc.
class MicropostsController < ApplicationController
before_action :set_micropost, only: [:show, :edit, :update, :destroy]

# GET /microposts
# GET /microposts.json
def index
@microposts = Micropost.all
end

# GET /microposts/1
# GET /microposts/1.json
def show
end

# GET /microposts/new
def new
@micropost = Micropost.new
end

# GET /microposts/1/edit
def edit
end

# POST /microposts
# POST /microposts.json
def create
@micropost = Micropost.new(micropost_params)

respond_to do |format|
if @micropost.save
format.html { redirect_to @micropost, notice: 'Micropost was successfully created.' }
format.json { render :show, status: :created, location: @micropost }
else
format.html { render :new }
format.json { render json: @micropost.errors, status: :unprocessable_entity }
end
end
end

# PATCH/PUT /microposts/1
# PATCH/PUT /microposts/1.json
def update
respond_to do |format|
if @micropost.update(micropost_params)
format.html { redirect_to @micropost, notice: 'Micropost was successfully updated.' }
format.json { render :show, status: :ok, location: @micropost }
else
format.html { render :edit }
format.json { render json: @micropost.errors, status: :unprocessable_entity }
end
end
end

# DELETE /microposts/1
# DELETE /microposts/1.json
def destroy
@micropost.destroy
respond_to do |format|
format.html { redirect_to microposts_url, notice: 'Micropost was successfully destroyed.' }
format.json { head :no_content }
end
end

private
# Use callbacks to share common setup or constraints between actions.
def set_micropost
@micropost = Micropost.find(params[:id])
end

# Never trust parameters from the scary internet, only allow the white list through.
def micropost_params
params.require(:micropost).permit(:content, :user_id)
end
end 

 15. The app/models/micropost.rb data model defines the foreign key relation to user table. And it ensures the content field is not empty and the maximum length is 140 characters:
class Micropost < ApplicationRecord
belongs_to :user
validates :content, length: { maximum: 140 },
presence: true
end

16. Finally, I pushed the project to Github:
$ git status
$ git add -A
$ git commit -m "Finish toy app"
$ git push

17. The URL location on Github is:
18. You can download and try on your Linux computer by typing these in your shell terminal:
$ git clone https://github.com/jimmy2046/toy_app.git
$ cd ~/toy_app
$ rails db:migrate
$ rails server

Create a New Repository and Push a Ruby on Rails project to Github

Here are the simplified procedures to create a new Github repository and push a new Ruby on Rails project to Github.

1. For example, a new Ruby on Rails project named toy_app is created using Linux shell terminal:

$ cd ~
$ rails _5.0.1_ new toy_app
$ cd toy_app/

2. (Optional): Install local Gem without production:
$ bundle install --without production

3. Put the Rails project under version control with Git:
$ git init
$ git add -A
$ git commit -m "Initialize repository"

4. In Firefox, go to Github https://github.com/YourGithubAccount/

5. In the Github's Create a new repository windows:
  • Give a repository name (e.g. toy_app)
  • (Optional): Write a Description if you like 
  • Public repository is free of charge as of the time of writing
  • Click the Create repository button



6. In the repository setup windows, I selected the push an existing repository from the command line method:
  • In Linux shell terminal:
$ git remote add origin https://github.com/jimmy2046/toy_app.git
$ git push -u origin master

7. Done. A new Ruby on Rails project is pushed to Github.

Adding a public SSH Key to Github

At first, I did not add my public SSH key to Github. I can still push my projects to Github without SSH key, but it seems that there are more and more people adding their SSH key to Github.

How to add a public SSH Key to Github:

1. Register a Github account if you don't have one.

2. Replace my name and email address in the following steps with the ones you used for your Github account:
git config --global color.ui true
git config --global user.name "YOUR NAME"
git config --global user.email "YOUR@EMAIL.com"
ssh-keygen -t rsa -b 4096 -C "YOUR@EMAIL.com"
3. Print your public SSH key using cat command:
cat ~/.ssh/id_rsa.pub
And then, the shell terminal will display a long text staring with ssh-rsa and ending with "YOUR@EMAIL.com"
ssh-rsa
blah blah blah
YOUR@EMAIL.com

4. In Firefox:
  • Go to URL: https://github.com/settings/keys
  • Click the New SSH Key button
  • In the Title text box, give it a name (e.g. Desktop)
  • In the Key text box, copy and paste your public SSH key from Step 3 to the text box
  • Click the Add SSH Key button

5. To check if it works, in Linux shell terminal, type:
ssh -T git@github.com
and type "yes" and the prompt.

6. You should get a message like this:
Hi jimmy2046! You've successfully authenticated, but GitHub does not provide shell access.
 
References:
https://gorails.com/setup/ubuntu/16.04#git


Thursday, April 20, 2017

Quote the Codes in Google Blogger


It is a good practice to Quote the codes when writing a blog post in Google Blogger. It is because programming source code and Linux shell command sometimes can be very long. It is better to make the codes can be scrolled horizontally for easier reading.

Google Blogger comes with the "Quote Text" button which allows the writer to quote specific text area. Blog write can customize the style of the quoted text using CSS.

To customize the style of quoted text in Google Blogger using CSS:

1. In Blogger Main Menu, select the Theme button:
 2. In Theme menu, click the Customize button:

3. In Blooger Theme Designer, click the Advanced button:

4. In the Advanced menu, scroll down to the bottom of the second column menu and select the Add CSS button:

5. In the Add custom CSS menu, I added the following CSS codes for my blog:
blockquote {
margin:1em 20px;
background: #ff6666;
padding: 8px 8px 8px 8px;
font-style: bold;
font-family: "Courier New";
white-space: nowrap;
overflow-x: auto;
}
6. Click the Apply to Blog button:


References:
How to Style Up Your Quotes in Blogger
https://www.maketecheasier.com/style-up-quotes-in-blogger/

Change the design of your blog
https://support.google.com/blogger/answer/176245?hl=en

how to scroll text area horizontally?
http://stackoverflow.com/questions/19292559/how-to-scroll-text-area-horizontally

Git - Commit local update to Github

1. For example, I want to update the README.md file on my local drive:
# README

This is the finished work from Getting Started with Rails on
http://guides.rubyonrails.org/getting_started.html

A User can access to the blog by either as registered user or as a guest.
A guest can:
* View the article list of the blog
* View the text (details) of each article
* Add a comment

A registered user with user name and password can also do the functions of a guest with these additional functions:
* Add a new article
* Edit an article
* Destroy (delete) an article
* Destroy a comment

2. We can see which files are in the staging area using the status command:
$ git status
 
3. Git is incredibly good at making branches, which are effectively copies of a repository where we can make (possibly experimental) changes without modifying the parent files.
$ git checkout -b modify-README
M    README.md
Switched to a new branch 'modify-README'

$ git branch
  master
* modify-README 

4. Edit the file: README.md and save the file.

5. Check the status of Git:
$ git status
On branch modify-README
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   README.md

no changes added to commit (use "git add" and/or "git commit -a") 

6. Commit the changes:
$ git commit -a -m "Improve the README file"
[modify-README 28c7a64] Improve the README file
 1 file changed, 19 insertions(+), 24 deletions(-)
 rewrite README.md (96%)
7. Merge to branch 'master'
$ git checkout master
Switched to branch 'master'
Your branch is up-to-date with 'origin/master'.
$ git merge modify-README
Updating bf0f534..28c7a64
Fast-forward
 README.md | 31 +++++++++++++------------------
 1 file changed, 13 insertions(+), 18 deletions(-)
8. (Optional) After you’ve merged in the changes, you can tidy up your branches by deleting the topic branch using git branch -d if you’re done with it:
$ git branch -d modify-README
Deleted branch modify-README (was 28c7a64).
9. Push the changes to Github. The command line will prompt for Github username and password:
$ git push
...
Username for 'https://github.com': jimmy2046
Password for 'https://jimmy2046@github.com':
Counting objects: 3, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 573 bytes | 0 bytes/s, done.
Total 3 (delta 1), reused 0 (delta 0)
remote: Resolving deltas: 100% (1/1), completed with 1 local object.
To https://github.com/jimmy2046/gettingstarttedwithrails
   bf0f534..28c7a64  master -> master
10. Go to your Github site (for example: https://github.com/jimmy2046/gettingstarttedwithrails) to check the changes are made on Github.

My First Ruby on Rails Book

My first Ruby on Rails book is Ruby on Rails Tutorial 3rd ed by Michael Hartl.



I bought this book because I found it by searching on Amazon.

And then I took advantage from Amazon search and spent fifty bucks to buy the book at my local Barnes and Noble bookstore. After I bought this book home, I found that I can read the book online for free at https://www.railstutorial.org/.


Anyway, I think this is a very Ruby on Rails book to start with. By the completion of the instructions from this book, readers can build a Twitter-like Web Application using the Ruby on Rails framework.

Tuesday, April 18, 2017

The Codes inside Getting Started with Rails

In my previous blog, I have demonstrated how to download my sample codes from https://github.com/jimmy2046/gettingstarttedwithrails. The sample codes are the finished work from Getting Started with Rails - http://guides.rubyonrails.org/getting_started.html.

I want to show the codes inside Getting Started with Rails very quickly and briefly.

~/gettingstarttedwithrails/app/views/welcome/index.html.erb shows the welcome page when a user goes to http://localhost:3000/
<h1>Hello, Rails!</h1>
<%= link_to 'My Blog', controller: 'articles' %>

~/gettingstarttedwithrails/config/routes.rb defines the routing table when a user calls a specific controller:
Rails.application.routes.draw do
#  get 'welcome/index'

  resources :articles do
    resources :comments
  end

  root 'welcome#index'

end

app/controllers/articles_controller.rb defines the actions when the user wants to do with the articles, such as index (list), new (create), edit, update. It also defines user name and password are required for all actions except index and show.
class ArticlesController < ApplicationController

  http_basic_authenticate_with name: "dhh", password: "secret", except: [:index, :show]

  def index
    @articles = Article.all
  end

  def show
    @article = Article.find(params[:id])
  end

  def new
    @article = Article.new
  end

  def edit
    @article = Article.find(params[:id])
  end

def create
  @article = Article.new(article_params)

  if @article.save
    redirect_to @article
  else
    render 'new'
  end
end

def update
  @article = Article.find(params[:id])

  if @article.update(article_params)
    redirect_to @article
  else
    render 'edit'
  end
end

def destroy
  @article = Article.find(params[:id])
  @article.destroy

  redirect_to articles_path
end

private
  def article_params
    params.require(:article).permit(:title, :text)
  end
end


app/views/articles/new.html.erb defines the format of the HTML page when a user wants to add a new article.
<h1>New article</h1>
<%= render 'form' %>
<%= link_to 'Back', articles_path %>

db/migrate/20170414223939_create_articles.rb defines the database meta data of the articles during migration:
class CreateArticles < ActiveRecord::Migration[5.0]
  def change
    create_table :articles do |t|
      t.string :title
      t.text :text

      t.timestamps
    end
  end
end

app/views/articles/show.html.erb specifies the format when a user reads the details of an articles:
<p>
  <strong>Title:</strong>
  <%= @article.title %>
</p>

<p>
  <strong>Text:</strong>
  <%= @article.text %>
</p>

<h2>Comments</h2>
<%= render @article.comments %>

<h2>Add a comment:</h2>
<%= render 'comments/form' %>

<%= link_to 'Edit', edit_article_path(@article) %> |
<%= link_to 'Back', articles_path %>

app/views/articles/index.html.erb lists out all the articles in the blog:
<h1>Listing articles</h1>
<%= link_to 'New article', new_article_path %>
<table>
  <tr>
    <th>Title</th>
    <th>Text</th>
    <th colspan="3"></th>
  </tr>

  <% @articles.each do |article| %>
    <tr>
      <td><%= article.title %></td>
      <td><%= article.text %></td>
      <td><%= link_to 'Show', article_path(article) %></td>
      <td><%= link_to 'Edit', edit_article_path(article) %></td>
      <td><%= link_to 'Destroy', article_path(article),
              method: :delete,
              data: { confirm: 'Are you sure?' } %></td>
    </tr>
  <% end %>
</table>

app/models/article.rb defines the foreign keys, minimum text length and not null column of the datatype:
class Article < ApplicationRecord
  has_many :comments, dependent: :destroy
  validates :title, presence: true,
                    length: { minimum: 5 }
end

app/views/articles/edit.html.erb renders the edit page in HTML when a registered user wants to edit an article:
<h1>Edit article</h1>
<%= render 'form' %>
<%= link_to 'Back', articles_path %>

app/views/articles/_form.html.erb defines the template of article. It encourages code reuse and avoid the repeating portion of files: new.html.erb and edit.html.erb:
<%= form_for @article do |f| %>

  <% if @article.errors.any? %>
    <div id="error_explanation">
      <h2>
        <%= pluralize(@article.errors.count, "error") %> prohibited
        this article from being saved:
      </h2>
      <ul>
        <% @article.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <p>
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </p>

  <p>
    <%= f.label :text %><br>
    <%= f.text_area :text %>
  </p>

  <p>
    <%= f.submit %>
  </p>

<% end %>

db/migrate/20170414232923_create_comments.rb specifies the data type and foreign key during database migration:
class CreateComments < ActiveRecord::Migration[5.0]
  def change
    create_table :comments do |t|
      t.string :commenter
      t.text :body
      t.references :article, foreign_key: true

      t.timestamps
    end
  end
end

app/models/comment.rb specifies the foreign keys of table comment:
class Comment < ApplicationRecord
  belongs_to :article
end

app/controllers/comments_controller.rb controls the actions related to comment model, such as create a new comment and destroy (delete) a comment. User name and password are required for destroying a comment:
class CommentsController < ApplicationController

  http_basic_authenticate_with name: "dhh", password: "secret", only: :destroy

  def create
    @article = Article.find(params[:article_id])
    @comment = @article.comments.create(comment_params)
    redirect_to article_path(@article)
  end

  def destroy
    @article = Article.find(params[:article_id])
    @comment = @article.comments.find(params[:id])
    @comment.destroy
    redirect_to article_path(@article)
  end

  private
    def comment_params
      params.require(:comment).permit(:commenter, :body)
    end
end

app/views/comments/_comment.html.erb re-factors the reused portion for displaying comments in files: show.html.erb
<p>
  <strong>Commenter:</strong>
  <%= comment.commenter %>
</p>

<p>
  <strong>Comment:</strong>
  <%= comment.body %>
</p>

<p>
  <%= link_to 'Destroy Comment', [comment.article, comment],
               method: :delete,
               data: { confirm: 'Are you sure?' } %>
</p>

app/views/comments/_form.html.erb re-factors the reused portion for submitting a comment in a form:
<%= form_for([@article, @article.comments.build]) do |f| %>
  <p>
    <%= f.label :commenter %><br>
    <%= f.text_field :commenter %>
  </p>
  <p>
    <%= f.label :body %><br>
    <%= f.text_area :body %>
  </p>
  <p>
    <%= f.submit %>
  </p>
<% end %>

These are the summary of the codes. Unlike web application development using C#, Microsoft Entity Framework, ASP or Java, the Model-View-Controller (MVC) model in Ruby on Rails requires very little or no programming logics, such as if-then-else statement, loops, SQL statement in traditional programming languages.

How to kill an abandoned process in Linux/Unix

I remembered it, then I forgot, then I remembered it, and then I forgot again. In case of a Linux/Unit process hang, I have to figure out ...