a Code Farmer

A blogging framework for hacker who farms

たのしいRuby 第4版 Reading Notes 0

I bought it three months ago, but never read it once since then. It is a Chinese-translated edition, because the original book is written in Japanese, which I am totally not familiar with, not even a word. I gonna to read it, write some notes and hope finish this book in not very long time.

Basics

“Hello World” is always a best friend of novice.
I am going to begin my journey of ruby with its basic output functions.

Standard outputs

1
2
3
4
5
6
7
8
9
10
11
12
=begin
ruby style's multi-line comments.
=end

print("Hello World\n"); #=> Hello World
# note: semicolon is not nesessary. ruby is not JAVA

puts('Hello World') #=> Hello World
# Same as above except "\n" is automatically added at the end of string.

p('Hello World') #=> 'Hello World'
# "p()" is simply output data in its natrual literal form.

Standard outputs revisited

1
2
3
4
5
6
7
a = 'World'

print("Hello ", a, "\n")
print("Hello #{a}\n")
puts("Hello #{a}")
#=> Hello World
# Three of above have no differences.

Loops

1
2
3
4
5
6
(10.times do |i|
    print(i)
end).times do
    print(i)
end
#=> 01234567890123456789

What?
Yes, that’s a use of chain rule, as times is a function that return itself, which is 10. 10 is a instance of Fixnum , which is also a subclass of Integer. Let’s take look at the big picture of Numeric class hiearchy in Ruby.1

Class Hiearchy
1
2
3
4
Numeric
    -> Integer            #-> method "times" lies in.
        -> Fixnum         #-> where 10 comes from.
        -> Bignum

Everything is object

That’s ruby, everything is object. Unlike java, there is no primitive type. You might wondering where print() comes from2. IO is where it comes from. There are three constant, STDIN, STDOUT and STDERR, which is pointed by ruby’s global variables, $stdin, $stdout and $sterr respectively.
print() is a alias of $stdout.print() provided by ruby’s Kernel module.

print() is alias of $stdout.print()
1
2
3
$stdout.print('I am a alias')
# is equivelent to
print('I am a alias')

Array and Hash

Beside String and Numeric two basic structure, Ruby has two more advanced data structure - Array and Hash. You can think of both as Java’s Listand Map.

Array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
names = ['sabonis', 'sprewell', 'shiren']
#=> ['sabonis', 'sprewell', 'shiren']

mix = ['sabonis', 29]
#=> Ruby supports different types in one container.

# Size of array
names.size()
#=> 3

# Iteration
names.each { |item|
    print(item, '')
}
#=> sabonis sprewell shiren
# {...} is same as "do ... end" block.
Hash
1
2
3
4
5
6
7
8
address = {:city => 'Taipei', :country => 'Taiwan'}

# Iteration
address.each {|key, value|
    puts(key, ' => ', value)
}
#=> city => Taipei
#=> country => Taiwan

:city is a Symbol of ruby, you can think of this as a lightweight version of String.

The same Symbol object will be created for a given name or string for the duration of a program's execution, regardless of the context or meaning of that name.

Per doc says, there will be one instance of Symbol with same name till program ended.

Notes

  1. For more information, see Ruby Reference

  2. See this post

Hello Sinatra

The setup

I choose to take recently most popular technology - Docker as our testing environment. One of benefit features of docker is that by using Dockerfile we have a descriptive and vcs-capable system environment, and that makes our life easier when we have migration needs.

Project Structure
1
2
3
4
5
/PROJECT_HOME/
├── Dockerfile
└── myapp.rb

0 directories, 2 files

Easy enough, just two files.

Dockerfile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# It’ll need ruby
FROM ruby:latest

MAINTAINER sabonis <sabonis.tw@gmail.com>

# The directory our main program` runs on.
VOLUME /server

# Relative path in which command executes.
WORKDIR /server

# Install sinatra
RUN gem install sinatra

# Defaut host of sinatra app is 127.0.0.1,
# that is not OK if your server needs port-forwarding.
CMD ruby myapp.rb -o 0.0.0.0

EXPOSE 4567
myapp.rb
1
2
3
4
5
6
#myapp.rb
require 'sinatra'

get '/' do
  'Hello world!'
end

The Hello

Console
1
2
3
4
5
6
7
8
9
10
11
12
# Build dockerfile to docker image.
sudo docker build -t YOUR_NAME/sinatra

# Run the image.
sudo docker run -dp 80:4567 \
                -v `pwd`:/server \
                YOUR_NAME/sinatra

# Test whether it works.
curl localhost
Hello world!%
#It works.

Octopress on Cygwin

It is painful when you are forced to use Windows as your programming environment. But there comes a rescuer Cygwin. With Cygwin, you have almost all tools that Unix have if install properly.

comment out following these lines

In the Rakefile
1
2
3
4
    #if (/cygwin|mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM) != nil
      #puts '## Set the codepage to 65001 for Windows machines'
      #`chcp 65001`
    #end

or you will get failed in the process of rake generate

LAMP on ARCH

If you are a web developer, you got to have these packages to be deployed on your ARCH. Those who use Windows, just keep playing CIVILIZATION V, no bothers.

Here is how

Installing part

Console
1
2
3
# update all packages
pacman -Syu;
pacman -S apache php php-apache mariadb

Configuring part

Console
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
vi /etc/httpd/conf/httpd.conf
# append following entries
LoadModule php5_module modules/libphp5.so
AddHandler php5-script php
Include conf/extra/php5_module.conf

vi /etc/php/php.ini
# uncomment this line
extension=mysqli.so

# setup mariadb, this is a interactive command, just follow the instruction
sudo mysql_secure_installation

# enable httpd at start-up
sudo systemctl enable httpd && systemctl restart httpd

and we are done here.

Sad

shoot, after yaourt -Syu, gnome is dead. I use LXDE now. but I want try gnome 3.10. so sad.

Fingerprint in Arch Linux

Saddly, it has been sold one day in 2014.

–edited Sun Apr 19 00:58:58 CST 2015

X230 is a cool laptop I ever used, not mentioned it backend by Arch Linux. Coolest thing is that it has figerprint device. You can just use “right-index-finger” to login into the system without any key pressed.

Console
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# check device status
lsusb

# you would find something like this below
.............
    .............
Bus 003 Device 003: ID 147e:2020 Upek TouchChip Fingerprint Coprocessor (WBF advanced mode)
    .............

# install related package
    pacman -S fprintd

# scan your fingerprint by this interactive command
    fprintd-enroll
# follow the instruction, and you are all set

Tmux-Powerline

Tmux is a very powerful terminal tool. I was once a user of Screen, but after giving Tmux a try. There is no going back…, at least, after changing its key binding to Screen and Vim alike. It is, though, powerful enough, folks just don’t content with what we have now. So here comes one of my favo plugins - Tmux-Powerline.

one big problem - Special Character

Use fontforge
1
2
3
sudo apt-get install python-fontforge             # install needed package
cd /usr/share/fonts/truetype/ubuntu-font-family/  # my os is Ubuntu 12.04
PATH_TO_FONTFORGE UbuntuMono-R.ttf                # no more garbled character

My Java Note

Write once, debug everywhere.

String class StringTest.java
1
"Jessica".subString(0, 4) // return Jess

How to Add a New Post on Octopress

Show me how

This post is for my memory-limited brain. Basically, three step needed.

Console
1
2
3
4
5
6
7
8
9
10
11
###1. Create a new post.
rake new_post\["POST_TITLE"\] # notice the backslash before square brackets
# new created post file will locate at place like line below. End with *.markdown.  

###2. Add markdown format stuff here
vi PATH_TO_OCTOPRESS/source/_posts/DATE-POST_TITLE.markdown

###3. Generate compliled files and push to server you defined before.
rake generate && rake deploy
# or
rake gen_deploy

And we are done here.

It Works.

Hello world, hello Taeyeon

Wow, this is a awesome blogging frame work. There are many funny pluggins and themes to play with. Maybe later. I just called it a day.