Erlang Variables

Erlang Variables

Dynamic Datatyping
Erlang is a dynamic datatyping programming language. That means that when “declaring” a variable you do not need to statically specify the datatypes. For example, this is how we declare and initialize an integer in Erlang:

1
I = 17.

This approach has both advantages and disadvantages. Advantages: when programming, it is fast and convenient as we don’t need to declare the variables datatypes. Disadvantages: In big projects it can lead to code readability problems unless well documented.

Variables Declaration
Erlang is influenced by Prolog. As with Prolog variables is a string consisting of letters, numbers and underscore characters, and beginning with an upper-case letter or underscore.

Example:

1
2
3
4
5
6
7
X
Name1
PhoneNumber
Phone_number
_
_Height
[H|_] = [1, , 2, 3]

Variable Assignement
Another feature that Erlang inherited from Prolog is binding with pattern matching. In a nutshell, a value is not assigned to a variable but bound with pattern matching. The most important thing is that variables in Erlang are single assignement, it mean that once bound to a value, their value cannot change for their lifetime.

Example (open terminator and try the following):

1
2
3
1> Age = 10.
10
2> Age = 11.

We will get an error:

** exception error: no match of right hand side value 11

The problem is that A is bound to the value 10, so Erlang tries to pattern match 10 with the value 11 which is impossible.

Introduction to Erlang and Chicagoboss Framework

Introduction to Erlang and Chicagoboss Framework

Erlang is a programming language used to build massively scalable soft real-time systems with requirements on high availability. Some of its uses are in telecoms, banking, e-commerce, computer telephony and instant messaging. Erlang’s runtime system has built-in support for concurrency, distribution and fault tolerance.

Erlang is the most advanced open-source server platform in existence, but it seems almost no one knows about it. Erlang can handle hundreds of thousands of simultaneous connections, it can spawn millions of simultaneous processes in under a second, server code can be upgraded, in production, without any interruption of service, and errors are handled in such a way that server crashes are extremely uncommon.

What is not to like? Why isn’t the entire world programming in Erlang? Well, Erlang is a functional language, which means that to implement any algorithms, you must use recursion instead of familiar “for” and “while” loops. Unlike every major scripting language, there is no built-in syntax for dictionaries or hash maps. And to actually write a functioning server, you must learn an additional layer of magic known as OTP. These barriers, in my opinion, have prevented Erlang from gaining much traction outside of Scandinavia.

Introduction to Erlang and Chicagoboss Framework

But Chicagoboss Framwork changes all that. It makes Erlang accessible to hackers who just want to write a reliable website in a nifty language. Boss uses code generation to get around the historic hash-map quandary, and takes care of all the OTP business so that you can focus on writing the features you need for your website. As for the supposed burdens of functional programming, I find that recursion is rarely necessary in workaday web programming; I would guess that 99% of server application code simply shuttles data to and from a database, so in the course of building a website, the pedestrian procedural programmer will hardly miss his “do/while” loops.

If you are an experienced web programmer, you’ll probably enjoy all the amenities that CB has to offer: an advanced ORM with support for database associations, sharding, and caching. lightning-fast templates compiled down to Erlang bytecode, automatic recompiling and in-browser error reporting, simple directives for reloads and redirects, routes for constructing URLs and handling requests, full frameworks for sending and receiving email, a built-in message queue, a framework for writing and running functional tests, and a first-of-its-kind event system for monitoring the data model.

In the end, by combining the Erlang platform with its own innovations, Chicagoboss Framwork makes websites a delight to develop and a joy to deploy. Boss applications can be written in the same time or less as equivalent Rails applications, and they will almost never crash or leak memory. Since the underlying networking is all asynchronous, you can easily write concurrent services, such as chat, that previously were only possible in callback-based frameworks (such as Nginx, Node.js, Twisted, or Perlbal).

The importance of this advancement cannot be overstated. It is now feasible for a very small team to develop and operate a database-driven, highly interactive, heavily trafficked website with very little capital outlay. Although Chicagoboss Framwork can’t tell you how to acquire users, the rest of this manual will show you everything you need to do to handle their requests and (with luck) fulfill their desires.

Reference: www.erlang.org, www.chicagoboss.org

The Erlang Learning Sequence

The Erlang Learning Sequence

While I was writing my first article (Why Erlang?). I realized that since Erlang is not a popular programming language it would be nice to start an introduction to The Erlang Learning Sequence.

I consider Erlang as a must-know language for an engineer that works with distributed systems and parallel programming. Believe me! in several cases Erlang is a problem solver.

I will keep posting of short and example based. The approximation of the posts that I intend to write is:

1. Introduction to Erlang & Chicagoboss Framework
2. Variables
3. Datatypes
4. Modules and Compiling
5. Functions
6. Guard
7. Recursion
8. Tail Recursion
9. Expressions
10. Predefined Module
11. List & List Module
12. List Comprehension
13. Concurrency (Processes)
14. Message Passing

So far so good, I will keep this list updated in case that I come up with new ideas! I hope I will convince you that Erlang worths for every software engineer’s attention. see ya! :)

Install Emacs Erlang Editor/IDE

Install Emacs Erlang Editor/IDE

Currently I personally use Emacs for programming in Erlang. There is an Erlang editing mode in Emacs. Well, I can help you to install Emacs and set Erlang mode in Emacs. So, let’s do it!

Install Emacs
Run commands below to install Emacs:

1
2
sudo apt-add-repository ppa:cassou/emacs
sudo apt-get install emacs24 emacs24-el emacs24-common-non-dfsg

Set Erlang Mode in Emacs
To set Erlang mode in Emacs add the following codes to file ~/.emacs:

.emacs
1
2
3
4
5
(defun my-erlang-mode-hook ()
  (setq inferior-erlang-machine-options '("-sname" "emacs"))
  (imenu-add-to-menubar "imenu")
)
(add-hook 'erlang-mode-hook 'my-erlang-mode-hook)

So far so good, hope the article could helped you. see ya! :)

Install Erlang Using Repository on Ubuntu

Install Erlang on Ubuntu

1. Adding Repository Entry
To add Erlang repository to your system, pls call the following commands:

1
2
wget http://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb
sudo dpkg -i erlang-solutions_1.0_all.deb

Or Adding the Repository Entry Manually
Add one of the following lines to your /etc/apt/sources.list:

1
2
3
deb http://packages.erlang-solutions.com/ubuntu trusty contrib
deb http://packages.erlang-solutions.com/ubuntu saucy contrib
deb http://packages.erlang-solutions.com/ubuntu precise contrib

And next, add the Erlang public key for apt-secure using following commands:

1
2
wget http://packages.erlang-solutions.com/ubuntu/erlang_solutions.asc
sudo apt-key add erlang_solutions.asc

2. Install Erlang
To install Erlang to your system, pls call the following commands:

1
2
sudo apt-get update
sudo apt-get install erlang

So far so good, hope you enjoyed the article. see ya! :)

Chicagoboss Publish/Subscribe

Chicagoboss Publish/Subscribe

In software architecture, publish–subscribe is a messaging pattern where senders of messages, called publishers, do not program the messages to be sent directly to specific receivers, called subscribers. Instead, published messages are characterized into classes, without knowledge of what, if any, subscribers there may be. Similarly, subscribers express interest in one or more classes, and only receive messages that are of interest, without knowledge of what, if any, publishers there are.

Pub/sub is a sibling of the message queue paradigm, and is typically one part of a larger message-oriented middleware system. Most messaging systems support both the pub/sub and message queue models in their API.

Actually Chicagoboss ships with a message queue service called BossMQ. The service consists of named channels which follow a publish/subscribe architecture; any Erlang process can publish or subscribe to any channel, and Erlang term can be sent as a message. Channels need not be explicitly created or destroyed; they are created on demand for publishers or subscribers, and automatically destroyed after a certain (configurable) amount of time. BossMQ runs in clustered configurations just as well as a single-machine setup.

Process

Develop Your Own Gem and Gemify Your Own Assets Using Rails Engine

Develop Your Own Gem and Gemify Your Own Assets Using Rails Engine

The Rails asset pipeline, powered by sprockets, compiles (sass, coffeescript, others), aggregates (combines multiple source files into one file for performance purposes), and post-processes (minimization, gzip’ing) your assets. And which make it easy to include versioned external assets as application dependencies as well.

External assets are made available in Rails via Rails engines. When the engine is loaded into your Rails application, the engine’s asset paths are added to your application’s load paths. This makes them available for require in your manifest files. An asset gem is just an absurdly simple engine.

You will find almost any JS or CSS library you want, already Gemified, but, if it is not the case, you can Gemify those libraries by your own, and I can help you with it. So, let’s do it!

Create a bare-bones Gem:
Bundler makes it simple to create the files and directories necessary for creating a gem. Run the following command to create and initialize a Git repository along with several template files for the gem:

1
bundle gem timeago-rails

This command will create basically the following tree:

1
2
3
4
5
6
7
8
9
10
├── Gemfile
├── lib
   ├── timeago
      └── rails
              └── version.rb
   └── rails.rb
├── LICENSE.txt
├── Rakefile
├── README.md
└── timeago-rails.gemspec

Versioning
timeago-rails is a gem packaged version of the timeago.js library. Its version should track the version of JavaScript library. Open /lib/timeago/rails/version.rb and set the version:

version.rb
1
2
3
4
5
module Timeago
  module Rails
    VERSION = "1.4.1"
  end
end

Turn the Gem into an Engine
Bundler created the gem as a standard Ruby module, but we want it to be a Rails Engine.

rails.rb
1
2
3
4
5
6
7
8
require "timeago/rails/version"

module Timeago
  module Rails
    class Engine < ::Rails::Engine
    end
  end
end

Well, the module is empty. All we’re doing here is declaring the gem as a Rails Engine. This will cause Rails to add its directories to the load path when the Gem is required.

Add the Assets (Javascript library, CSS, Image) in the Gem
We’re going to create the directory /vendor/images/, /vendor/javascripts/, vendor/stylesheets/ and place the source for the timeago.js plugin there:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
├── Gemfile
├── lib
   ├── timeago
      └── rails
              └── version.rb
   └── rails.rb
├── LICENSE.txt
├── Rakefile
├── README.md
├── timeago-rails.gemspec
└── vendor
         └── assets
                  ├── images
                  ├── javascripts
                               └── timeago.js
                  └── stylesheets

Test
Moving to a sample Rails application, we can include the gem in our host application by adding it to the Gemfile using the path option:

Gemfile
1
gem "timeago-rails", path: "../timeago-rails"

Since we included an asset that needs to be included in the Rails assets, we have to take one more step and instruct the user to add the following to their app/assets/javascripts/application.js file:

application.js
1
//= require timeago-rails

This directive actually refers to the app/assets/javascripts/timeago.js file we included in our gem.

Type command below to make sure timeago.js is included in sample Rails application:

1
curl http://localhost:3000/assets/timeago.js

The curl command should return the contents of the timeago.js file if everything is correctly.

README.md
Make a simple readme file with the Gem as documentation.

Push to GitHub & RubyGems
Create a GitHub repository for the Gem, stage all of your commits, commit, and push the code to GitHub.

If you’ve never published a gem on RubyGems before, you’ll need to sign up for an account there. Your account settings will contain an API key that should be copied to ~/.gem/credentials.

Publishing your gem is as simple as:

1
rake release

So far so good, hope you enjoyed the article. see ya! :)

Deploy Ruby on Rails Application to a Ubuntu Server

Tools for Monitoring Performance in Ruby on Rails Application

Assumes you have Ruby on Rails application already.

Setup Ruby Version, Unicorn and Capistrano
Specifiy a ruby version for your app by creating a new file in the root of your app called “.ruby-version” that includes:

.ruby-version
1
2.1.4

Make the following changes to the Gemfile:

Gemfile
1
2
3
4
ruby '2.1.4'

gem 'unicorn'
gem 'capistrano-rails', group: :development

Type command below to install gems:

1
bundle install

Type command below to install binstubs for capistrano:

1
bundle binstubs capistrano

Configure Capistrano
Type command below to initialize capistrano:

1
bin/cap install

Add the following below require ‘capistrano/deploy’ in the Capfile in the root of your app:

Capfile
1
require 'capistrano/rails'

Add or Replace this configuration in config/deploy.rb file:

deploy.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
set :application, 'myapp'
set :repo_url, 'git@github.com:bunlong/myapp.git'
set :deploy_to, '/opt/www/myapp'
set :user, 'deploy'
set :linked_dirs, %w{log tmp/pids tmp/cache tmp/sockets}

namespace :deploy do
  %w[start stop restart].each do |command|
    desc 'Manage Unicorn'

    task command do
      on roles(:app), in: :sequence, wait: 1 do
        execute "/etc/init.d/unicorn_#{fetch(:application)} #{command}"
      end
    end
  end

  after :publishing, :restart
end

After the configuration in /config/deploy/production.rb with your server ip or domain name:

production.rb
1
2
3
role :app, %w{deploy@0.0.0.0}
role :web, %w{deploy@0.0.0.0}
role :db,  %w{deploy@0.0.0.0}

Configure Unicorn
Create a new file config/unicorn.rb with the following contents:

unicorn.rb
1
2
3
4
5
6
7
8
9
root = "/opt/www/myapp/current"
working_directory root
pid "#{root}/tmp/pids/unicorn.pid"
stderr_path "#{root}/log/unicorn.log"
stdout_path "#{root}/log/unicorn.log"

listen "/tmp/unicorn.myapp.sock"
worker_processes 1
timeout 30

Comment out production username and password from config/database.yml:

database.yml
1
2
3
production:
  <<: *default
  database: myapp_production

Type command below to push changes to git:

1
2
3
git add .
git commit -m 'Added settings to deploy app'
git push origin master

Type command below to create a secret to be used on the server:

1
bin/rake secret

On the server setup the secret by modify /home/deploy/.bashrc with the following contents:

.bashrc
1
export SECRET_KEY_BASE=[REPLACE WITH YOUR SECRET]

On the server restart nginx, type command below:

1
sudo service nginx restart

Deploy
Type command below to make sure capistrano is connected to the server:

1
bin/cap production git:check

Type command below to make sure can deploy or not:

1
bin/cap production deploy:check

Type command below for deploying:

1
bin/cap production deploy

If you need to run db:seed, log into server as the deploy user and run following:

1
cd /opt/www/myapp/current ; bin/rake RAILS_ENV=production db:seed

If you are having problems, try running a console on the server, log in as deploy user and run the following:

1
cd /opt/www/myapp/current ; bin/rails c production

Private Doesn’t Apply to Class Method and Define Method

Ruby - Check for nil Without Using an Explicit if

Ruby’s private keyword might do a lot less than you think.

The “private” does not apply to class methods defined on self

This does not make anything private:

1
2
3
4
5
6
class Klass
  private
  def self.print
    'Hello'
  end
end

You need to use private_class_method instead:

1
2
3
4
5
6
7
class Klass
  def self.print
    'Hello'
  end

  private_class_method :print
end

The “private” does not apply to define_method

This does not make anything private:

1
2
3
4
5
6
class Klass
  private
  define_method :print do
    'Hello'
  end
end

You need to use private with an argument instead:

1
2
3
4
5
6
7
class Klass
  define_method :print do
    'Hello'
  end

  private :print
end

Erlang & Chicago Boss Framework

Erlang


You may remember my first article post about Erlang. I’ve shared a short introduction to the Erlang programming language and it’s concurrency philosophy in the article. There are some highlights of that Erlang already include:

High Availability and Reliability
- Simple and consistent error recovery and supervision hierarchiess.
- Built-in fault tolerance (Let it fail/crash! - Do not program defensively).
- Hot code loading during runtime (software upgrades with zero downtime).

Scalability and Heterogeneity
- Run on multiple platforms, HetNet support.
- Network aware runtime, out-of-the-box distributed architectures.
- Very light-weight processes, highly scalable transparent or explicit concurrency.
- Awesome transparent multi-core support:

Less Effort
- Functional programming language, high abstraction level, concise readable programs.
- When compared with any imperative language, 4–20 times less code written for same application.
- Suitable for rapid prototyping.
- Impressive and powerful libraries and middleware (Open Telecom Platform - OTP).

So, what is the “dark side” of Erlang for most developers? The correct answer is “The Erlang syntax!”.

In my first week with Erlang, I had no idea what I’ve been doing while coding something. Believe me, if you fall into the Erlang world from any imperative language, you’d feel like me. The problem could be good to discuss, but that’s beside the point.

Chicago Boss framwork: Start small, dream big

In software development, using a framework is almost a rule for fast, clean, easy readable and standardized coding. Chicago Boss (http://www.chicagoboss.org/) is a framework that is heavily inspired by Rails. Set up and use Chicago Boss is easy as falling off a log. Chicago Boss allows you to code with the aforementioned standards in Erlang. Plus, offers conveniences of modern web development, including WebSocket and Comet. Basic features of Chicago Boss listed below:
- 100% asynchronous I/O
- Support for Erlang and Elixir code
- BossDB: Database connection layer with an advanced ORM which with built-in support for Mnesia, MongoDB, MySQL, PostgreSQL, Riak and Tokyo Tyrant.
- BossCache: Database caching layer
- BossMQ: Cluster–wide, channel–based message queue
- BossRouter: URL router
- BossSession: Session storage layer
- BossNews: Event listener, model event system
- BossMail: Built-in email server
- Django and Jade template support
- Very clean controllers as result of pattern matching
- Auto document generation for models
- An useful admin interface
- Automatic code reloading

We’ll cover almost all of features of Chicago Boss during developing an applicatioin. So far so good let enjoy in developing a simple application with Chicago Boss framwork. See ya!!! :)