Ruby : Passing data to including module

Sometimes but not often in programming career in Ruby, you need to pass some sort of data to the module that is being included into your class. Firstly, I wondered how would I do that. Luckly Ruby is the only language ( I think) where you can do anything to solve problems.

The only limitation is your imagination and the Language never stops you doing anything. Since you can modify anything,  you end up with your own version of Ruby which you have created using Metaprogramming. Continue reading


Setting aliases in Unix system

Its so handy to execute long commands or series of commands with just a word in Unix systems like Linux, Mac, BSDs, etc. In Bash’s ~/.bashrc you can see a line like

 # ~/.bash_aliases, instead of adding them here directly.
if [ -f ~/.bash_aliases ]; then
 . ~/.bash_aliases

What it says is, you can have a file ~/.bash_aliases in which you can define alias to commands you need to run every once and while.

You can define alias like

# ~/.bash_aliases
alias greproute='rake routes | grep '
alias myshortcut='cd ~/projects/myproject && bundle exec rails c'

Solution 2

If you wished not to update the .bash_aliases file, you can have those lines defined in .bashrc file itself.

Note: The above mentioned commands/procedure is not gonna work for shells other than Bourne Again Shell(Bash).

For ZShell users

Open your ~/zshrc file in nano editor or any and paste the following line.

if [ -f ~/.bash_aliases ]; then
 . ~/.bash_aliases

Make sure, you have followed the instruction illustrated above to define aliases and have ~/.bashaliases

This works because syntax for bash and zsh are almost same.

Rails : Common SMTP settings


# config/initializers/smtp_settings.rb

ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
  :address              => "",
  :port                 => "587",
  :user_name            => "",
  :password             => "yyy",
  :authentication       => "plain",
  :enable_starttls_auto => true



ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings   = {
    :address              => '',
    :port                 => '587',
    :user_name            => ENV['smtp_username'],
    :password             => ENV['smtp_password'],
    :authentication       => 'plain',
    :enable_starttls_auto => true

Many hosting providers and ISPs block port 25 as a default practice. When trying to connect to remember that ports 25, 2525, 587, and 465 are all available for use.

We recommend port 587 to avoid any rate limiting that your server host may apply.

Setting attributes and their meaning

Allows detailed configuration for :smtp delivery method:

  • :address – Allows you to use a remote mail server. Just change it from its default "localhost" setting.
  • :port – On the off chance that your mail server doesn’t run on port 25, you can change it.
  • :domain – If you need to specify a HELO domain, you can do it here.
  • :user_name – If your mail server requires authentication, set the username in this setting.
  • :password – If your mail server requires authentication, set the password in this setting.
  • :authentication – If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of :plain (will send the password in the clear), :login (will send password Base64 encoded) or :cram_md5 (combines a Challenge/Response mechanism to exchange information and a cryptographic Message Digest 5 algorithm to hash important information)
  • :enable_starttls_auto – Detects if STARTTLS is enabled in your SMTP server and starts to use it. Defaults to true.
  • :openssl_verify_mode – When using TLS, you can set how OpenSSL checks the certificate. This is really useful if you need to validate a self-signed and/or a wildcard certificate. You can use the name of an OpenSSL verify constant (‘none’, ‘peer’, ‘client_once’, ‘fail_if_no_peer_cert’) or directly the constant (OpenSSL::SSL::VERIFY_NONE, OpenSSL::SSL::VERIFY_PEER, …).



Install and Configure Monit web interface

Install Monit

Monit is easiest to install through apt-get:

$ sudo apt-get install monit

Once monit downloads, you can add programs and processes to the configuration file:

$ sudo nano /etc/monit/monitrc

Monit can be started up with a command that then keeps it running in the background

$ monit

Typing monit status displays monit’s details:

The Monit daemon 5.3.2 uptime: 1h 25m 

System 'myhost.mydomain.tld'
  status                            Running
  monitoring status                 Monitored
  load average                      [0.03] [0.14] [0.20]
  cpu                               3.5%us 5.9%sy 0.0%wa
  memory usage                      26100 kB [10.4%]
  swap usage                        0 kB [0.0%]
  data collected                    Thu, 30 Aug 2012 18:35:00

Configure Monit

Monit is very easy to use nearly out of the box. By default, it is set up to check that services are running every 2 minutes and stores its log file in “/var/log/monit.log”.

These settings can be altered at the beginning of the configuration file in the set daemon and set logfile lines respectively.

Web Service

Monit comes with it’s own web server running on port 2812. To configure the web interface, find and uncomment the section that begins with set httpd port 2812. Once the section is uncommented, write in your server’s IP or domain name as the address, allow anyone to connect, and then create a monit user and password

set httpd port 2812
    use address  # only accept connection from localhost
    allow        # allow localhost to connect to the server and
    allow admin:monit      # require user 'admin' with password 'monit'

Once this is configured, monit should reload and reread the configuration file, and the web interface will be available:

$ monit reload

When you are done, try

You will see a dialogbox appear in the browser.

General Monit Scripts


# /etc/monit/conf-available/sidekiq
check process sidekiq_thepact_staging0 with pidfile "/home/deployer/www/staging/shared/tmp/pids/"  
  start program = "/bin/su - deployer -c 'cd /home/deployer/www/staging/current && /usr/local/rvm/bin/rvm default do bundle exec sidekiq --config /home/deployer/www/staging/current/config/sidekiq.yml --index 0 -e staging -d'" with timeout 30 seconds  
  stop program = "/bin/su - deployer -c 'cd /home/deployer/www/staging/current && /usr/local/rvm/bin/rvm default do bundle exec sidekiqctl stop /home/deployer/www/staging/shared/tmp/pids/'" with timeout 110 seconds  group thepact-sidekiq-0


# /etc/monit/conf-available/pg
check process postgres with pidfile /var/run/postgresql/
 group database
 start program = "/etc/init.d/postgresql start"
 stop program = "/etc/init.d/postgresql stop"
 if failed unixsocket /var/run/postgresql/.s.PGSQL.5432 protocol pgsql
 then restart


# /etc/monit/conf-available/puma
check process puma with pidfile /var/www/myapp/production/shared/tmp/pids/
 group www

 start program   = "/bin/su - shiva -c '~/.rvm/bin/rvm default do bundle exec puma -C /var/www/myapp/production/shared/puma.rb --daemon'"
 stop program    = "/bin/su - shiva -c 'pumactl stop -P /var/www/myapp/production/shared/tmp/pids/'"
 restart program = "/bin/su - shiva -c 'pumactl restart -P /var/www/myapp/production/shared/tmp/pids/'"


# /etc/monit/conf-available/puma
check process puma with pidfile /var/www/myapp/production/shared/tmp/pids/
 group www
 start program   = "/bin/su - shiva -c '~/.rvm/bin/rvm default do bundle exec puma -C /var/www/myapp/production/shared/puma.rb --daemon'"
 stop program    = "/bin/su - shiva -c '~/.rvm/bin/rvm default do bundle exec pumactl -S /var/www/myapp/production/shared/tmp/pids/puma.state stop'"
 restart program = "/bin/su - shiva -c '~/.rvm/bin/rvm default do bundle exec pumactl -S /var/www/myapp/production/shared/tmp/pids/puma.state restart'"

Using the scripts

By default Monit doesnot load conf-scripts in conf-available. You have to copy the scripts to conf-enabled to have them executed by Monit. So, we are going to link those files that folder instead of copying/duplicating them. Its a good practice.

$ sudo ln /etc/monit/conf-available/puma /etc/monit/conf-enabled/puma

This will link the file there, same file will act as if it is there too.



RVM Installation issue : Public Key download issue

You might have gone through the RVM installation and tried this command

$ gpg --keyserver hkp:// --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3

This command actually downloads the verified public key and verifies the integrity of the installer script file.


$ gpg --keyserver hkp:// --recv-keys D39DC0E3

gpg: requesting key D39DC0E3 from hkp server
gpg: keyserver timed out
gpg: keyserver receive failed: keyserver error



Despite of that error, you execute the following command

$ \curl -sSL | bash -s stable --ruby

# Output 

gpg: Signature made मंगलबार 29 मार्च 2016 using RSA key ID BF04FF17
gpg: Can't check signature: No public key
Warning, RVM 1.26.0 introduces signed releases and automated check of signatures when GPG software found.
Assuming you trust Michal Papis import the mpapis public key (downloading the signatures).

GPG signature verification failed for '/home/john/.rvm/archives/rvm-1.27.0.tgz' - ''!
try downloading the signatures:

gpg2 --keyserver hkp:// --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3

or if it fails:

command curl -sSL | gpg2 --import -

the key can be compared with:

The solution is there in the error message. Try

$ gpg2 --keyserver hkp:// --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3

If it fails, try this

$ curl -sSL | gpg2 --import -

And try this again

$ \curl -sSL | bash -s stable --ruby


You are done,

Thanks for visiting


Debugging: What is binding in Ruby?

You might have thought always whenever you wrote code binding.pry in your application to debug your application.

People often say “do binding to see whats going on”. Actually you are not doing binding but prying into the binding. So, its good to say “Please pry into that binding”.

But, what is binding in the first place? Continue reading


Issue tracking in production via Gitlab Ruby API

It’s so easy for you to track production issues/exceptions with Gitlab. It has super sexy issue board and Issue management UI along with RESTful API. Thankfully we need not write REST API, however Ruby API is sufficient. There is an awesome Ruby Gem written by `@NARKOZ` (

Configuration example:

gem 'gitlab'
# in config/initializers/gitlab_config.rb
Gitlab.configure do |config|
  config.endpoint       = '' # API endpoint URL, default: ENV['GITLAB_API_ENDPOINT']
  config.private_token  = 'qEsq1pt6HJPaNciie3MG'       # user's private token or OAuth2 access token, default: ENV['GITLAB_API_PRIVATE_TOKEN']
  # Optional
  # config.user_agent   = 'Custom User Agent'          # user agent, default: 'Gitlab Ruby Gem [version]'
  # config.sudo         = 'user'                       # username for sudo mode, default: nil

You can find API for issues here

Example Library I wrote

This should handler the rest. Make sure you include this module in ApplicationController

# in controller/concerns/exception_handler.rb
module ExceptionHandler
  extend ActiveSupport::Concern
  class InvalidRequest < StandardError;  end

  included do
    unless Rails.application.config.consider_all_requests_local
      rescue_from InvalidRequest,
                  ArgumentError, with: :handle_unauthorized_requests


  def handle_unauthorized_requests(error)
    render 'errors/unauthorized', status: 400, layout: 'static', locals: {error: error}

  def create_issue_in_gitlab(error)
    title = "#{error.class} : #{error.message}"

    description = "## Details\n"
    description << "**DateTime**: #{}  \n"
    description << "**TimeZone**: #{}  \n"
    description << "**Environment**: #{Rails.env}  \n"
    description << "**UserID**: #{current_user &&}  \n"
    description << "**Requested From**: #{request.ip}  \n"
    description << "**Request Referrer URL**: #{request.referrer}  \n"
    description << "**Requested URL**: #{request.url}  \n"

    description << "## Request\n"
    description << "```ruby\n"
    description << "parameters: #{request.filtered_parameters}\n"
    description << "```\n"

    description << "## Session Dump\n"
    description << "```ruby\n"
    description << "#{session_dump}\n"
    description << "```\n"

    description << "## Backtrace\n"
    description << "```ruby\n"
    description << "#{error.backtrace[0..25].join("\n")}\n"
    description << "```\n"

    # TODO Move this task to ActiveJob
    # project_id is integer you get from gitlab for your project
    #  I figured out using
    #    > Gitlab.projects  # in rails console after configuring the gem
    #    this gives array of projects, you will get ID for project
    Gitlab.create_issue(ENV['gitlab_issifix_project_id'], title,
                        {description: description, labels: 'System Generated, Bug, Production'})

  def session_dump
    keys = ['_csrf_token', 'session_id', 'warden.user.user.key', 'warden.user.user.session'] { |key| "#{key}: #{session[key]}" }.join("\n")


Then you should be seeing issues created in your project.

Screenshot of an example Issue

Screenshot from 2016-09-04 22:44:56