Tuesday, June 30, 2015

Check Amazon S3 Credentials

1. gem install aws-s3
2. In IRB console : require 'aws/s3'
AWS::S3::Base.establish_connection!(access_key_id: 'abcd', secret_access_key: 'secret')

It would be nice to steal code from aws-s3 gem to test if the credentials is valid or not.

ERROR: "https://rubygems.org" is not allowed by the gemspec, which only allows "TODO: Set to 'http://mygemserver.com'"


Not able to publish gem to rubygems.org


Delete the following lines from your-gem.gemspec file.

  if spec.respond_to?(:metadata)
    spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
    raise "RubyGems 2.0 or newer is required to protect against public gem pushes."

how to use active support outside of rails

Error : NoMethodError: undefined method `hours' for 1:Fixnum


1. bundle open activesupport
2. Search for 'def hours', it is found in core_ext/numeric/time.rb
3. Add require 'active_support/core_ext/numberic/time.rb'

This is better than doing : require 'active_support/all'

Saturday, June 27, 2015

How to use Simplecov in gem development

1. Add the simplecov gem and start before anything else in test_helper.rb

$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'simplecov'


require 'rasam'
require 'minitest/autorun'

2. You can mark private methods as:
    # :nocov:
  to exclude from test coverage.
3. Run : rake test

4. Open coverage/index.html

Friday, June 26, 2015

How I resolved confusing tests and production code

Pair Ranking is very well defined problem solving technique. When my code become convoluted I had to switch my perspective to that of the user to improve the code and the tests. Read more about it here: TDD Beyond Basics : Outside In Perspective. This also shows you an example of how you could use this gem.

Searching for a given element in an array of arrays in Ruby

How to pull the number 3 from this list by searching for the value 'c'.

records =

search_for = 'c'

Solution 1:

test = records.select{ |x| x[0] == search_for }

p test[0][1]

Solution 2:

p records.assoc(search_for).last

Playing with Rails 4.2.3

zepho-mac-pro:blog zepho$ rails g scaffold article title
      invoke  active_record
      create    db/migrate/20150626235457_create_articles.rb
      create    app/models/article.rb


zepho-mac-pro:blog zepho$ rake db:migrate
== 20150626235457 CreateArticles: migrating ===================================
-- create_table(:articles)
   -> 0.0015s
== 20150626235457 CreateArticles: migrated (0.0016s) ==========================

zepho-mac-pro:blog zepho$ rails c
Loading development environment (Rails 4.2.3)
2.2.2 :001 > Article
 => Article (call 'Article.connection' to establish a connection)
2.2.2 :002 > Article.count
   (0.1ms)  SELECT COUNT(*) FROM "articles"
 => 0

Thursday, June 25, 2015

Pair Ranking Algorithm

require 'highline/import'
require "pp"
require 'rasam'

include Rasam

options = ask("Enter your choices (or a blank line to quit):",
lambda { |ans| ans =~ /^-?\d+$/ ? Integer(ans) : ans} ) do |q|
  q.gather = ""

@pr = PairRank.new(options)
@saved_combinations = Array.new(@pr.combinations)
combinations = Array.new(@pr.combinations)

pair = combinations.shift

def get_user_choice_for(pair)
  choose do |menu|
    menu.prompt = "Please choose your favorite: "

    pair.each do |c|
      menu.choice(c) do

        rationale = ask("Why?  ")


        rc = RationalChoice.new(pair, c, rationale)

loop do
  p pair  
  break if combinations.empty?
  pair = combinations.shift

@pr.decisions.each do |d|
  p d.to_s

p @pr.score_for('A')
p @pr.score_for('B')
p @pr.score_for('C')

def handle_ties(pair)
  choose do |menu|
    menu.prompt = "Please choose your favorite: "

    pair.each do |c|
      menu.choice(c) do

        rationale = ask("Why?  ")


        rc = RationalChoice.new(pair, c, rationale)

loop do
  p 'Handling a tie'
  if @pr.tied_pair.empty?
    @pr.decisions.each do |d|
      p d.to_s
    p @pr.score_for('A')
    p @pr.score_for('B')
    p @pr.score_for('C')
    p @pr.tied_pair

find numbers that are same in an array ruby

a = [0,1,2,2,3,3]
x = a.find_all { |e| a.count(e) > 1 }
p x

Wednesday, June 24, 2015

Pair Ranking Gem Released

Select a single winner using votes that express preferences. This can also be used to create a sorted list of winners. rasam gem

Create Gem and Publish to Rubygems

$gem build rasam.gemspec
$gem push rasam-0.1.0.gem

Generate all combinations of a given length for a list of items

In Ruby 2.2.2:

 a = [1,2,3,4]
 => # 

We need to call to_a on this enumerator:

 a = ['A', 'B', 'C', 'D']
 => ["A", "B", "C", "D"]
> a.combination(2).to_a
 => [["A", "B"], ["A", "C"], ["A", "D"], ["B", "C"], ["B", "D"], ["C", "D"]]

How to provide a default value for all elements in a hash

a = Hash.new(0)
 => {}
> a['x']
 => 0

`require': cannot load such file -- minitest/autorun

Install Minitest gem by running: bundle install

Eliminate spaces, -, +, *, /, = and parentheses in a string


str = "Revenue - Costs * (1 + Profitpercentage)"
p str.scan(/[A-Za-z]+/)

at http://rubyplus.biz/

You will see:

["Revenue", "Costs", "Profitpercentage"]

How to delete nested hash elements based on the elements properties

data = {

p data

data['records'].delete_if{ |h| %w(Val1 Val2).include?(h['title']) }

p data


{"total_records"=>3, "records"=>[{"title"=>"Val1", "coins"=>1}, {"title"=>"Val2", "coins"=>1}, {"title"=>"Val3", "coins"=>1}]}
{"total_records"=>3, "records"=>[{"title"=>"Val3", "coins"=>1}]}

Two HERE Docs in Ruby 2.2.2

data = [
<<'EOT1', <<'EOT2'
more text
and more

p data

An error occurred while installing json (1.6.1), and Bundler cannot continue.

Make sure that `gem install json -v '1.6.1'` succeeds before bundling.
zepho-mac-pro:dynamic-menus zepho$ gem install json -v 1.6.1
Building native extensions.  This could take a while...
ERROR:  Error installing json:
ERROR: Failed to build gem native extension.

    /Users/zepho/.rvm/rubies/ruby-2.2.2/bin/ruby -r ./siteconf20150624-48402-1w7o7yz.rb extconf.rb
checking for ruby/re.h... yes
checking for ruby/encoding.h... yes
creating Makefile

make "DESTDIR=" clean

make "DESTDIR="
compiling generator.c
generator.c:952:47: error: too few arguments provided to function-like macro invocation
    VALUE result = rb_str_new(FBUFFER_PAIR(fb));
generator.c:952:11: warning: incompatible pointer to integer conversion initializing 'VALUE' (aka 'unsigned long') with an expression of type 'VALUE (const char *, long)';
    VALUE result = rb_str_new(FBUFFER_PAIR(fb));
          ^        ~~~~~~~~~~
1 warning and 1 error generated.
make: *** [generator.o] Error 1

make failed, exit code 2

Gem files will remain installed in /Users/zepho/.rvm/gems/ruby-2.2.2@dmenu/gems/json-1.6.1 for inspection.
Results logged to /Users/zepho/.rvm/gems/ruby-2.2.2@dmenu/extensions/x86_64-darwin-11/2.2.0/json-1.6.1/gem_make.out

Resolution: Downgrade ruby from 2.2.2 to 2.1

Could not find coffee-script-source-1.1.3 in any of the sources


bundle update --source coffee-script-source

Top 6 Ruby Links for June 24, 2015

1. How to build a rails 5 api only and backbone application

2. Provisioning a Server for Rails Stack using Sunzi Gem

3. How to Setup Vagrant for Rails Development

4. Using the Rails 5 Attributes API Today, in Rails 4.2

5. Render Markdown views with Redcarpet and Pygment in Rails

6. Subscribing for events in rails_event_store

Tuesday, June 23, 2015

How to check postgres version

There are two ways:

sudo -u postgres psql
psql (9.4.4)
Type "help" for help.

postgres=# \q

deploy@localhost:~/apps/your-app/current$ psql --version

psql (PostgreSQL) 9.4.4

rbenv: version `ruby' is not installed on production

1. env | grep PATH

Check that rbenv shims is in the path:



See `rbenv help ' for information on a specific command.
For full documentation, see: https://github.com/sstephenson/rbenv#readme
deploy@localhost:~/apps/carmel_production/current$ rbenv versions
rbenv: version `ruby' is not installed
deploy@localhost:~/apps/carmel_production/current$ rbenv 2.2.2
rbenv: no such command `2.2.2'
deploy@localhost:~/apps/carmel_production/current$ rbenv local 2.2.2
deploy@localhost:~/apps/carmel_production/current$ rbenv versions
* 2.2.2 (set by /home/deploy/apps/carmel_production/current/.ruby-version)
deploy@localhost:~/apps/carmel_production/current$ ruby -v
ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-linux]
deploy@localhost:~/apps/carmel_production/current$ bundle exec unicorn -D -c /home/deploy/apps/carmel_production/shared/config/unicorn.rb -E production

Capistrano Deployment fails due to rake db:migrate failure

The cause is that the database does not exist.

Create a Database on the Server Manually

sudo -u postgres createdb --owner=postgres your-database-name

To go to postgres console:

sudo -u postgres psql

FATAL: password authentication failed for user "your-user-idl"

The following steps work for a fresh install of postgres 9.4 on Ubuntu 14.04

By default, postgres creates a user named 'postgres'. We log in as that user, and give that user a password.

$ sudo -u postgres psql
Enter password: topseckret


to exit postgres.

Then we connect as 'postgres'. The -h localhost part is important: it tells the psql client that we wish to connect using a TCP connection (which is configured to use password authentication), and not by a PEER connection (which does not care about the password).

$ psql -U postgres -h localhost

PG::ConnectionBad: FATAL: Peer authentication failed for user

Specify the host in database.yml:

  adapter: postgresql
  encoding: unicode
  database: postgresql
  pool: 5
  host: localhost
  username: postgresql
  password: secret

bitbucket Permission denied (publickey). capistrano

You should already have your ssh keys added to your Bitbucket account. From the root of the rails project run:
1. ssh-add ~/.ssh/id_rsa
2. cap production deploy

sudo stderr: sudo: no tty present and no askpass program specified

1. Login to the server as root
2. Add the following line to the end of sudoers file by doing : visudo

Installing pg gem on Mac OS 10.9.5

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    /Users/bparanj/.rvm/rubies/ruby-2.1.5/bin/ruby -r ./siteconf20150623-1849-zuaatt.rb extconf.rb 
checking for pg_config... no
No pg_config... trying anyway. If building fails, please try again with
checking for libpq-fe.h... no
Can't find the 'libpq-fe.h header
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:

extconf failed, exit code 1

Gem files will remain installed in /Users/bparanj/.rvm/gems/ruby-2.1.5@carmel/gems/pg-0.18.2 for inspection.
Results logged to /Users/bparanj/.rvm/gems/ruby-2.1.5@carmel/extensions/x86_64-darwin-14/2.1.0-static/pg-0.18.2/gem_make.out
An error occurred while installing pg (0.18.2), and Bundler cannot continue.

Make sure that `gem install pg -v '0.18.2'` succeeds before bundling.


1. Install http://postgresapp.com/
2. Move postgres from Downloads folder to the Applications folder
3. gem install pg -- --with-pg-config=/Applications/Postgres.app/Contents/Versions/9.4/bin/pg_config

Monday, June 22, 2015

Upgrading Ruby using Sunzi

# rbenv
# $1: ruby version

# This condition will not work if we want to upgrade Ruby. Fix is needed.
if [ -d /usr/local/rbenv ]; then
  echo 'rbenv already installed, skipping.'
  git clone git://github.com/sstephenson/rbenv.git /usr/local/rbenv
  echo 'export RBENV_ROOT=/usr/local/rbenv' >> /etc/profile.d/rbenv.sh
  echo 'export PATH="$RBENV_ROOT/bin:$PATH"' >> /etc/profile.d/rbenv.sh
  echo 'eval "$(rbenv init -)"' >> /etc/profile.d/rbenv.sh
  chmod +x /etc/profile.d/rbenv.sh
  source /etc/profile.d/rbenv.sh
  pushd /tmp
    git clone git://github.com/sstephenson/ruby-build.git
    cd ruby-build
  echo "Compiling Ruby. Grab some hot chocolate, this will take a while..."
  rbenv install $1
  rbenv global $1
  gem install bundler --no-ri --no-rdoc
  rbenv rehash

I had to blow the entire /usr/local/rbenv to force the upgrade. Just specifying the version in sunzi.yml:

  environment: production
  ruby_version: 2.2.2

does not work.

Using Sunzi Gem to Provision Your Server in Minutes

Sunzi is the easiest server provisioning utility designed for mere mortals. If Chef or Puppet is driving you nuts, try Sunzi! Here is step-by-step instructions on  : Provisioning a Server using Sunzi

Deploy Rails 4.1 App with Sunzi and Capistrano 3 Notes from Screencast

1. Ignore database.yml and secrets.yml by adding it to .gitignore
2. gem install sunzi (Does not have to be in Gemfile)
3. cd config
4. sunzi create 
5. In a temp directory : git clone git@github.com:crslade/sunzi-recipes.git sunzi-template
6. In the project directory

cd config/sunzi/
cp ~/temp/sunzi-template/files/* files
cp ~/temp/sunzi-template/recipes/* recipes
cp ~/temp/sunzi-template/sunzi.yml .
cp ~/temp/sunzi-template/install.sh .

7. sunzi.yml has password. Do not checkin into git. Same thing for deploy_key.

Add sunzi.yml and deploy_key to config/sunzi/.gitignore

# Ignore sensitive data

8. [todo/config/sunzi]

cp sunzi.yml sunzi.sample.yml
cp files/deploy_key files/deploy_key.sample (Deploy user can login without password)

9. cp ~/.ssh/id_rsa.pub files/deploy_key 

10. define database name, password, deploy_user = deploy, app_name=todo in sunzi.yml

11. Manual Steps. Some of these can be automated. Since it is one time thing, it is ok to do it manually.

Login to VPS. Create a linode instance by selecting the plan, location. Add the public ssh key of laptop so that you can login to the instance as a root user.

   $cat ~/.ssh/id_rsa.pub 
   #mkdir .ssh
   #paste id_rsa.pub content in .ssh/authorized_keys
   #chown -R root:root .ssh
   #chmod 700 .ssh
   #chmod 600 .ssh/authorized_keys
   $ssh root@ 
   should not prompt for any password
12. Copy the IP address from your Linode dashboard and ssh root@ip-address 

You should be able to login into the instance without providing any password.

13. sunzi compile

14.  sunzi deploy ip-address

This will take 10 to 15 minutes.

15. Hit the IP address on the browser. You will see the nginx static page.

16. ssh deploy@ip-address should take into the instance without requiring any password.

17. github.com/talkingquickly/capistrano-3-rails-template copy the clone url and download this project.

[temp]$ git clone url cap-template


[todo] Gemfile

# Use unicorn as the app server
gem 'unicorn'

# Use Capistrano for deployment
group :development do
 gem 'capistrano-rails'
 gem 'capistrano-bundler'
 gem 'capistrano-rbenv', "~> 2.0"

Refer the : https://github.com/crslade/todo-sunzi-deploy or temp/todo-sunzi-deploy

bundle install


bundle exec cap install

Capfile :

# Load DSL and Setup Up Stages
require 'capistrano/setup'

# Includes default deployment tasks
require 'capistrano/deploy'

# Includes tasks from other gems included in your Gemfile
# For documentation on these, see for example:
#   https://github.com/capistrano/rvm
#   https://github.com/capistrano/rbenv
#   https://github.com/capistrano/chruby
#   https://github.com/capistrano/bundler
#   https://github.com/capistrano/rails
# require 'capistrano/rvm'
require 'capistrano/rbenv'
# require 'capistrano/chruby'
require 'capistrano/bundler'
require 'capistrano/rails/assets'
require 'capistrano/rails/migrations'

# Loads custom tasks from `lib/capistrano/tasks' if you have any defined.
Dir.glob('lib/capistrano/tasks/*.cap').each { |r| import r }
Dir.glob('lib/capistrano/**/*.rb').each { |r| import r }

20. In project root directory:

cp ~/temp/cap-template/lib/capistrano/*.rb lib/capistrano
cp ~/temp/cap-template/lib/capistrano/tasks/* lib/capistrano/tasks
cp ~/temp/cap-template/config/deploy.rb config/deploy.rb
cp ~/temp/cap-template/config/deploy/production.rb config/deploy/production.rb
mkdir config/deploy/shared
cp ~/temp/cap-template/config/deploy/shared/* config/deploy/shared

21. Edit deploy.rb

application name
repo url
ruby version

linked_files secrets.yml
config_files secrets.yml


Create deploy/shared/secrets.yml.erb

Copy secrets.yml into the erb file and retain only production.

23. Find out how to setup staging server. Leave staging.rb as it is for now.

24. In deploy/production.rb

Specify the server_name as IP address or as domain name if DNS is already setup. The IP also goes into server line.

25. cap production deploy:setup_config

26. ssh deploy@ip-add

cd apps/todo_prod/shared/config

cp secrets.sample.yml to secrets.yml
cp database.sample.yml database.yml



commit all changes to git and push it to bitbucket.


cap production deploy


Reload the webpage. The application should be running.

30. To troubleshoot:

Unicorn log files. Output of deployment. nginx log files and app log files.

nginx error log file location

You can find the location of the nginx error log file in your ngnix configuration file:

/etc/nginx# cat nginx.conf
user www-data;
worker_processes  4;

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

In this case, the error log is in /var/log/nginx/ directory.

Rails Basics : Using Dropdowns

I have created a sample project with detailed instructions on how to create drop-downs in Rails 4.2.2 and Ruby 2.2.2 https://rubyplus.com/articles/2501

RVM PATH Problem

Warning! PATH is not properly set up, '/Users/zepho/.rvm/gems/ruby-2.1.2/bin' is not at first place,
         usually this is caused by shell initialization files - check them for 'PATH=...' entries,
         it might also help to re-add RVM to your dotfiles: 'rvm get stable --auto-dotfiles',
         to fix temporarily in this shell session run: 'rvm use ruby-2.1.2'.

Resolution: rvm get stable --auto-dotfiles

Pongal Gem Released

Pongal is a valid US state generator that can be used in Geocoding applications. Check it out: https://rubygems.org/gems/pongal

How to generate a random number in a range in Ruby 2.2.2


This will generate random numbers 0 to 4. It is inclusive of the lower and upper bound in the range.

Sunday, June 21, 2015

Implicit Vs Explicit Return in Ruby

You can run the following code at RubyPlus Code Editor:

Implicit return:

def times_ten(integer)
  integer * 10

p times_ten(1)

Explicit return:

def times_ten(integer)
  return integer * 10

p times_ten(2)

Saturday, June 20, 2015

dyld: Library not loaded

dyld: Library not loaded: /usr/local/lib/libruby.1.9.1.dylib
  Referenced from: /usr/local/bin/ruby
  Reason: image not found

Trace/BPT trap: 5

Resolution: gem install bundler

Wednesday, June 17, 2015

Top 6 Ruby Links for June 17, 2015

1. How a Bug in My Ruby Code Cost Code School $13,000

2. Docker Basics : Running a Nginx in a Container

3.  Ruby events (meetups, conferences, camps, etc.) from around the world

4. When should you use DateTime and when should you use Time?

5. Understanding the rails-jquery CSRF vulnerability (CVE-2015-1840)

6. Mutation testing for Ruby

VirtualBox 4.3 and Vagrant 1.7.2

Vagrant has detected that you have a version of VirtualBox installed
that is not supported. Please install one of the supported versions
listed below to use Vagrant:

4.0, 4.1, 4.2

Reason : VirtualBox 4.3.28 is not compatible with Vagrant 1.0.5

1. Check :

vagrant --version
Vagrant version 1.0.5

2. Delete the Vagrant folder in Applications.

3. Download the latest vagrant from : http://www.vagrantup.com/downloads

I installed vagrant 1.7.2. This is compatible with VirtualBox 4.3

Sunday, June 14, 2015

Wednesday, June 10, 2015

Using Custom Fonts in Rails 4.2

There is no need to configure anything as long as you have fonts copied to app/assets/fonts directory. Make sure to use the font-url to use custom fonts. You can see this font in action at RubyPlus. My style.css.scss looks like this :

@font-face {
font-family: 'OpenSans-Bold';

@font-face {
font-family: 'OpenSans-BoldItalic';

@font-face {
font-family: 'OpenSans-ExtraBold';

@font-face {
font-family: 'OpenSans-ExtraBoldItalic';

@font-face {
font-family: 'OpenSans-Italic';

@font-face {
font-family: 'OpenSans-Light';

@font-face {
font-family: 'OpenSans-LightItalic';

@font-face {
font-family: 'OpenSans-Regular';

@font-face {
font-family: 'OpenSans-Semibold';

@font-face {
font-family: 'OpenSans-SemiboldItalic';

Top 6 Ruby Links for June 10, 2015

1.  Wrapper for the confreaks API. Browse and download convention videos from the command line.

2.  Object Oriented Design Basics : Open Closed Principle

3. Nothing is Something

4.  Functional Programming dictionary with Ruby #1/2

5. Cells 4.0 – Goodbye Rails! Hello Ruby!

6. How to Deal With and Eliminate Flaky Tests 

Monday, June 08, 2015

ssh-copy-id: command not found

1. If it is already installed: brew unlink ssh-copy-id
2. brew install ssh-copy-id