Friday, December 05, 2014

Upgrading from Rails 4.1.4 to Rails 4.1.8

Problem when upgrading from Rails 4.1.4 to Rails 4.1.8

rails -v
Bundler is using a binstub that was created for a different gem.
This is deprecated, in future versions you may need to `bundle binstub rails` to work around a system/bundle conflict.
Rails 4.1.8


Fix:
$rm -rf bin/*
$bundle exec rake rails:update:bin
zepho-mac-pro:lafon zepho$ rails -v
Rails 4.1.8


Monday, November 24, 2014

Deploying a Rails App on Google App Engine

Deploying a Rails Webapp on GAE should be a piece of cake right? Due to lack of good documentation, it is not that easy. I had to dig around to find the versions of the software installed for Ruby Stack One-Click Deploy.

Here is some useful information to access installed software components.
Apache web server:  

Configuration directory: /etc/apache2
Default website directory: /var/www
Command to start Apache web server: sudo service apache2 start
Command to stop Apache web server: sudo service apache2 stop

Passenger:

Help command: passenger --help
Install directory: /usr/local/rvm/gems/ruby-2.1.1/gems/passenger-4.0.48

MySQL:

Command to access MySQL: mysql -u root -p
Command to start MySQL service: sudo service mysql start
Command to stop MySQL service: sudo service mysql stop

RVM, Ruby and Rails:

RVM Help command: rvm
Rails help command: rails -h
RVM install directory: /usr/local/rvm
Ruby install directory: /usr/local/rvm/src/ruby-2.1.1
Rails install directory: /usr/local/rvm/gems/ruby-2.1.1/gems/rails-4.1.4

Git:
Help command: git --help

Saturday, November 22, 2014

bin/rails:6: warning: already initialized constant APP_PATH

I was getting this error in Rails 4.2 beta when I started the rails server. Solution: run : rake rails:update:bin from rails project directory.

git Illegal instruction: 4 mac 10.7.5

Download the git for Mac 10.7.5  and restart your terminal.

Friday, November 14, 2014

Stripe API Capybara Test Failures

I was getting Stripe::InvalidRequestError: You must supply either a card or a customer id error. To fix this, make sure js is true in your integration test like this:

feature 'Guest Checkout' do
  scenario 'Complete purchase of one product', js: true do
    visit products_show_path
    click_link 'Buy Now'
   
    fill_in "Card Number", with: '4242424242424242'  
    page.select '10', from: "card_month"
    page.select '2029', from: 'card_year'
    click_button 'Buy Now'
   
    expect(page).to have_content('Receipt')
  end
end

Thursday, November 13, 2014

Base Ball Player Statistics

Overview:  For this scenario, we have been asked to write an application that will be used to provide information about baseball player statistics.  Approach this problem as if it is an application going to production.  We don't expect it to be perfect (no production code is), but we also don't want you to hack together a throw-away script.  This should be representative of something that you would be comfortable releasing to a production environment.  Also, spend whatever amount of time you think is reasonable.  If you don't get all the requirements completed, that's ok.  Just do the best you can with the time that you have available.  You may use whatever gems, frameworks and tools that you think are appropriate, just provide any special setup instructions when you submit your solution.

Assumptions:  All requests currently are based on data in the hitting file.  Future requests of the system will require data from a pitching file as well.  Consider this in the design.

Requirements: When the application is run, use the provided data and calculate the following results and write them to STDOUT.

1) Most improved batting average( hits / at-bats) from 2009 to 2010.  Only include players with at least 200 at-bats.
2) Slugging percentage for all players on the Oakland A's (teamID = OAK) in 2007. 
3) Who was the AL and NL triple crown winner for 2011 and 2012.  If no one won the crown, output "(No winner)"

Formulas:
Batting average = hits / at-bats
Slugging percentage = ((Hits – doubles – triples – home runs) + (2 * doubles) + (3 * triples) + (4 * home runs)) / at-bats
Triple crown winner – The player that had the highest batting average AND the most home runs AND the most RBI in their league. It's unusual for someone to win this, but there was a winner in 2012. “Officially” the batting title (highest league batting average) is based on a minimum of 502 plate appearances. The provided dataset does not include plate appearances. It also does not include walks so plate appearances cannot be calculated. Instead, use a constraint of a minimum of 400 at-bats to determine those eligible for the league batting title.


Data:  All the necessary data is available in the two csv files attached:

Batting-07-12.csv – Contains all the batting statistics from 2007-2012.  
Column header key:
AB – at-bats
H – hits
2B – doubles
3B – triples
HR – home runs
RBI – runs batted in

Master-small.csv – Contains the demographic data for all baseball players in history through 2012.


Please note: We are looking for you to demonstrate you knowledge related to common software practices to include reusability, portability, and encapsulation – to name a few. Work submitted should be in project form and implemented as you were implementing any production solution.


Tuesday, November 11, 2014

How to share files between Virtual Box Ubuntu with Mac OS host computer

1. Create a folder in your Mac home directory, let's say ubuntu-sf.
2. Install guest additions. Click Devices -> Guest Additions and run the installer.
3. Reboot VM
4. Select the Ubuntu image on VM, go to Settings -> Shared Folders
5. Browse to the folder on your Mac you want to share (ubuntu-sf). Name the shared folder (ubuntu-sf)
6. On Ubuntu terminal, run : sudo adduser your-username vboxsf
7. On Ubuntu terminal run: sudo mount -t vboxsf ubuntu-sf /home/bparanj/ubuntu-sf
   Here ubuntu-sf is the name of the shared folder we created in step 5. /home/bparanj/ubuntu-sf is the folder in the
   Ubuntu.


References

How to share files between Virtual Box Ubuntu and host computer
How to automatically mount a folder and change ownership from root in virtualbox


some of the partitions you created are too small ubuntu 12.04 LTS Precise Pangolin

I was getting this error during installation of Ubuntu on Virtual Box. Solution: Increase the hard disk size from default 8GB to something higher. It worked for 45GB.

Tuesday, November 04, 2014

How to get web_console working in Rails 4.2.beta4 project

1. Add the gem to Gemfile.

group :development do
  gem 'web-console', '2.0.0.beta3'
end

2. bundle

3. You can go to the web console by going to the URL : http://localhost:3000/console

You will also see the web console on the bottom of the browser. You can experiment with the Rails environment loaded.

4. You can add "<%= console %>" to any views and play with the web console.

If you restart the server. You need to reload the page to get a new active console session.

For more details : Web Console Ruby Gem

Problem installing nokogiri on Mac OS 10.7.5

Problem: Make sure that `gem install nokogiri -v '1.6.3.1'` succeeds before bundling.

Solution: bundle config build.nokogiri --use-system-libraries
Then run : bundle

libv8 and therubyracer installation problems on Mac OS 10.7.5

The error message is : Make sure that `gem install libv8 -v '3.16.14.7'` succeeds before bundling.
Solution: gem install libv8 -v '3.16.14.7' -- --with-system-v8

Make sure that `gem install therubyracer -v '0.12.1'` succeeds before bundling.
Solution : Change the Gemfile to specify the libv8 version:

gem 'libv8', '3.11.8.13' 
and run bundle

Sunday, October 19, 2014

Copy to Clipboard in Linux

1. Install xclip : sudo apt-get install xclip
2. Copy test.txt to clipboard : cat test.txt | xclip
3. Acess the text from the clipboard: xclip -o

Reference:

1. Copy Output of a Command to Clipboard

Wednesday, September 24, 2014

Changing PDF Meta Data in Ruby

According to the home page of pdf-toolkit gem :

pdf-toolkit allows you to access pdf metadata in read-write in a very simple way, through the pdftk commandline tool.

1. Install pdftk version 2.02

$ pdftk -version

pdftk 2.02 a Handy Tool for Manipulating PDF Documents
Copyright (c) 2003-13 Steward and Lee, LLC - Please Visit: www.pdftk.com
This is free software; see the source code for copying conditions. There is
NO warranty, not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

2. gem install pdf-toolkit

3. Read or Write pdf meta data.

require 'pdf/toolkit'

pdf = PDF::Toolkit.open('tmux_p3_0.pdf')
#puts pdf.public_methods(false).sort

puts pdf.author
pdf.author='Daffy Duck'
if pdf.save
  'PDF meta-data saved successfully'
else
  'Failed to save pdf meta-data'
end
# save! to raise exception on failure

puts "after change"
puts "Author"
puts pdf.author
puts 'Title'
puts pdf.title
puts 'Subject'
puts pdf.subject
puts 'Page count'
puts pdf.page_count
puts 'Creator (Publisher)'
puts pdf.creator
puts 'Created At'
puts pdf.created_at
puts 'keywords'
puts pdf.keywords
puts 'producer'
puts pdf.producer
puts 'version'
puts pdf.version
puts 'Updated at'
puts pdf.updated_at

4. Verify the meta-data in Preview -> Tools -> Show Inspector. You will see the author, title, subject, producer, creator, creation date, updated date, number of pages etc.

5. Read the tests in the pdf-toolkit source code to see the available methods.

Tuesday, September 23, 2014

Fast Typing, IDE shortcuts, Fast Coding

It does not matter how fast you type in the keyboard, know every short-cut in the IDE, never use the mouse or how fast you can code. Remember : It's garbage in, garbage out.

The quality of software depends on:

1. Quality of your thinking.
2. Learning from your mistakes. Did you learn from your own mistakes?
3. Are you making new mistakes or oblivious and making the same old mistakes over and over again?
4. Are you learning from the mistakes of others to minimize making mistakes in the first place?
5. Are you learning to master the best practices?
6. Are you reading books by : Martin Fowler, Alaister Coburn, Eric Evans, Robert Martin etc? Are you applying it to your projects?



Friday, September 19, 2014

wrong number of parameters 2 for in stylesheet_link_tag rails

This error occurs with an ambiguous error message. It does not show the line number of the source where the cause of the problem resides. This happened due to sass-rails dependency on sass gem. Since the sass gem was not declared in the Gemfile, the sass-rails upgraded sass gem to 3.4.4 which broke the application layout. By locking the sass gem to a lower version in the Gemfile:

gem sass, "~ 3.2.1"

The sass-rails picked up this version that works.

Monday, September 01, 2014

The Scientific Method of Troubleshooting

Notes from the presentation by Blithe Rocher.

Set of Techniques for Acquiring Knowledge.
Methodical
Systematic

1. Define the Problem
Expected behavior
Actual behavior
Criteria for success

2. Do Your Research
Know your environment
Read the literature
Discussions
Make it fail

3. Establish a Hypothesis
4. Design the Experiment
Divide and conquer
Limit the variables
Try something weird
Hierarchy of Blame

4. Gather Data
Current status
Read the error message

5. Analyze Your Results
 Problem Solved?
Learn anything?
Understand the Why
Future Experiments
Embrace the Success

6. Keep a Good Lab Notebook
You won't remember
Logs aren't enough
Commit messages
Update the docs
Contribute
Blog it
Share the knowledge



Friday, August 22, 2014

How to play with ActiveModel validators in the rails console

1. bundle open activemodel
2. Open the validator.rb file.
3. You can see the comments that shows you how to mixin the validators. Once you mixin, you can add any validator and define a dummy method for the attribute to play with it in the irb:

class Person
  include ActiveModel::Validations
  SSN_REGEX = /your ssn regex goes here/
  validates_format_of :ssn, with: SSN_REGEX
 
 
  def ssn   
    111-11-1111
  end
end

4. Change the ssn method to invalid ssn to test your regex.
 

Thursday, August 21, 2014

How to install Exception Notification gem in Rails 4.1

1. Add the gem to Gemfile:

gem 'exception_notification'



bundle install

2. In config/environments/production.rb:

Whatever::Application.config.middleware.use ExceptionNotification::Rack,
  :email => {
    :email_prefix => "[Whatever] ",
    :sender_address => %{"notifier" },
    :exception_recipients => %w{exceptions@example.com}
  }

3. Configure ActionMailer, in config/environments/production.rb:

I am using Sendgrid SMTP API so:

config.action_mailer.delivery_method = :smtp

If you have sendmail installed on the production server:

config.action_mailer.delivery_method = :sendmail

4. In production.rb:
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true

How to install pdftk on Mac OS

You can download the installer from https://www.pdflabs.com/tools/pdftk-server/

After installation, open a new terminal and check installation:

$ pdftk --version

pdftk 2.02 a Handy Tool for Manipulating PDF Documents
Copyright (c) 2003-13 Steward and Lee, LLC - Please Visit: www.pdftk.com
This is free software; see the source code for copying conditions. There is
NO warranty, not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$

Wednesday, August 20, 2014

How to create .ruby-version and .ruby-gemset in RVM

rvm --create --ruby-version use ruby-2.1.2@r42
Reference: Create .ruby-version and .ruby-gemset

How to install latest version of Rails

gem install rails --version=4.2.0.beta1

How to check if ElasticSearch is running

By default elastic search runs on port 9200.

$ curl http://localhost:9200
{
  "ok" : true,
  "status" : 200,
  "name" : "White Pilgrim",
  "version" : {
    "number" : "0.90.13",
    "build_hash" : "249c9c5e06765c9e929e92b1d235e1ba4dc679fa",
    "build_timestamp" : "2014-03-25T15:27:12Z",
    "build_snapshot" : false,
    "lucene_version" : "4.6"
  },
  "tagline" : "You Know, for Search"
}

1. gem install rest-client

require 'rest-client'
RestClient.get('http://localhost:9200')


$ irb
> require 'rest-client'
 => true
> x = RestClient.get('http://localhost:9200')
 => "{\n  \"ok\" : true,\n  \"status\" : 200,\n  \"name\" : \"White Pilgrim\",\n  \"version\" : {\n    \"number\" : \"0.90.13\",\n    \"build_hash\" : \"249c9c5e06765c9e929e92b1d235e1ba4dc679fa\",\n    \"build_timestamp\" : \"2014-03-25T15:27:12Z\",\n    \"build_snapshot\" : false,\n    \"lucene_version\" : \"4.6\"\n  },\n  \"tagline\" : \"You Know, for Search\"\n}\n"
> x['ok']
 => "ok"
> JSON.parse(x)
 => {"ok"=>true, "status"=>200, "name"=>"White Pilgrim", "version"=>{"number"=>"0.90.13", "build_hash"=>"249c9c5e06765c9e929e92b1d235e1ba4dc679fa", "build_timestamp"=>"2014-03-25T15:27:12Z", "build_snapshot"=>false, "lucene_version"=>"4.6"}, "tagline"=>"You Know, for Search"}

Tuesday, August 19, 2014

How to configure the secret_key_base in Rails 4.1

1. Define an environment variable in .bashrc or .profile on the server:

export SECRET_KEY_BASE='a long string generated by running rake secret'

2. In secrets.yml file :
secret_key_base=<%= ENV['SECRET_KEY_BASE'] %>

3. MyBlog::Application.config.secret_key_base = Rails.application.secrets.secret_key_base

Remember: After deployment all the old sessions will become invalid.

Monday, August 18, 2014

How to add lib directory to the load path in Rails 4.1

   Uncomment the line :  config.autoload_paths += %W(#{config.root}/lib) in application.rb

Thursday, August 07, 2014

Installing Redis on Mac

~ $brew install redis
==> Downloading https://downloads.sf.net/project/machomebrew/Bottles/redis-2.8.9.mavericks.bottle.tar.gz
######################################################################## 100.0%
==> Pouring redis-2.8.9.mavericks.bottle.tar.gz
==> Caveats
To have launchd start redis at login:
    ln -sfv /usr/local/opt/redis/*.plist ~/Library/LaunchAgents
Then to load redis now:
    launchctl load ~/Library/LaunchAgents/homebrew.mxcl.redis.plist
Or, if you don't want/need launchctl, you can just run:
    redis-server /usr/local/etc/redis.conf
==> Summary
 /usr/local/Cellar/redis/2.8.9: 10 files, 1.3M

Wednesday, July 30, 2014

Saturday, July 26, 2014

Installing a specific version of elastic search


brew search elasticsearch

$ brew install homebrew/versions/elasticsearch090
Cloning into '/usr/local/Library/Taps/homebrew/homebrew-versions'...
remote: Reusing existing pack: 2230, done.
remote: Total 2230 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (2230/2230), 714.24 KiB | 12.00 KiB/s, done.
Resolving deltas: 100% (1260/1260), done.
Checking connectivity... done.
Tapped 149 formulae
==> Downloading https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-0.90.13.tar.gz
######################################################################## 100.0%
==> Caveats
Data:    /usr/local/var/elasticsearch/elasticsearch_bparanj/
Logs:    /usr/local/var/log/elasticsearch/elasticsearch_bparanj.log
Plugins: /usr/local/var/lib/elasticsearch/plugins/

To have launchd start elasticsearch090 at login:
    ln -sfv /usr/local/opt/elasticsearch090/*.plist ~/Library/LaunchAgents
Then to load elasticsearch090 now:
    launchctl load ~/Library/LaunchAgents/homebrew.mxcl.elasticsearch090.plist
Or, if you don't want/need launchctl, you can just run:
    elasticsearch --config=/usr/local/opt/elasticsearch/config/elasticsearch.yml
==> Summary
🍺  /usr/local/Cellar/elasticsearch090/0.90.13: 31 files, 19M, built in 6.8 minutes

Thursday, July 24, 2014

Installing Javascript Runtime

1. Uninstalled manually installed nodejs on Ubuntu 12.04. Since my server is managed by Moonshine. Manual installation is a bad idea.

sudo apt-get remove nodejs 

2. Add :

gem 'execjs'
gem 'therubyracer'
to the Gemfile

3. Bundle and deploy.

Installing ElasticSearch using brew

$ brew install elasticsearch
Error: elasticsearch-0.90.9 already installed
To install this version, first `brew unlink elasticsearch'
$ brew unlink elasticsearch
Unlinking /usr/local/Cellar/elasticsearch/0.90.9... 3 symlinks removed
$ brew install elasticsearch
==> Downloading https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-1.2.1.tar.gz
######################################################################## 100.0%
==> Caveats
Data:    /usr/local/var/elasticsearch/elasticsearch_bparanj/
Logs:    /usr/local/var/log/elasticsearch/elasticsearch_bparanj.log
Plugins: /usr/local/var/lib/elasticsearch/plugins/

ElasticSearch requires Java 7; you will need to install an appropriate JDK.

To reload elasticsearch after an upgrade:
    launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.elasticsearch.plist
    launchctl load ~/Library/LaunchAgents/homebrew.mxcl.elasticsearch.plist
==> Summary
🍺  /usr/local/Cellar/elasticsearch/1.2.1: 31 files, 21M, built in 5.6 minutes

Tuesday, July 22, 2014

Missing `secret_key_base` for 'production' environment, set this value in `config/secrets.yml`

1. Specify the secret_key_base by using figaro gem. Search on this blog for how to do that.

Installing Phusion Passenger 4.0.45 using Moonshine in Ubuntu 12.04

1. Login to phusion passenger account.
2. Download the license
3. Move the license file to vendor/plugins/moonshine/lib/moonshine/manifest/rails/templates file. The name of the file is the same as the downloaded file name which is passenger-enterprise-license
4. Add the following to the moonshine.yml file:

:passenger:
  :max_pool_size: 3
  :version: 4.0.45 # This is 2 versions behind because according to the moonshine source code, this is the blessed version.
  :enterprise: true
  :download_token: copy-your-download-token-from-passenger-account-here
  :rolling_restarts: true
   
5. Check in the code to bitbucket and do :
   cap deploy

No such file to load -- shadow puppet (LoadError) moonshine error

Copy the following lines to application.rb file.

    # don't attempt to auto-require the moonshine manifests into the rails env
    config.paths['app/manifests'] = 'app/manifests'
    config.paths['app/manifests'].skip_eager_load!

Installing NodeJS using Moonshine Plugin

1. plugger install git://github.com/iros/moonshine_nodejs.git
2. Add
recipe :nodejs
 
to the application_manifest.rb 
 
This will fail gloriously. 
 
Install it by:
 
apt-get install python-software-properties
apt-add-repository ppa:chris-lea/node.js
apt-get update
apt-get install nodejs
node -v
 
should show : v0.10.20
 
Reference : NodeJS installation on Ubuntu 12.04     

How to display flash messages using Twitter Bootstrap 3 in Rails 4.1

1. Copy the following helper method to app/helpers/application_helper.rb

  def bootstrap_class_for(flash_type)
    case flash_type
    when "success"
      "alert-success"   # Green
    when "error"
      "alert-danger"    # Red
    when "alert"
      "alert-warning"   # Yellow
    when "notice"
      "alert-info"      # Blue
    else
      flash_type.to_s
    end
  end

2. Create a shared folder in app/views

3. Copy the following code to app/views/_flash_messages.html.erb

<% flash.each do |type, message| %>
 

   
    <%= message %>
 

<% end %>

4. In your layout, add the line :         <%= render '/shared/flash_messages' %>
   above the yield call.

5. Set the flash messages in any of your controllers and you will see the flash messages displayed.

Reference : Stolen from gist.

Final Cut Pro 10.1.2 Crash Course in 10 Minutes

Recording Voice Over

Step 1 : Detach the audio from the video

1. Select the clip from the timeline window.
2. Go to Clip --> Detach audio
3. Select the audio and click delete.

Step 2 : Record Voice Over

1. Click the timeline where you want to start recording the voice over.
2. Go to window, Record Voice Over.
3. Click Record
4. Click the red button to stop recording.

If you make a mistake select the audio track in TL and delete.

Speeding up the Video

1. Select Blade from the dropdown.
2. Select the start and end of the video by using the blade.
3. Modify --> Retime --> 4x
4. Go back to the drop down and select the pointer.

Note : Select before you change the timing so that the rest of the video is unaffected.

Deleting Part of the Clip

1. Select the blade from the drop down.
2. Pick the starting and the end point of the clip
3. Select the pointer from the drop down.
4. Select the clip to reject and click delete.

Audio Enhancement

1. Select the audio
2. Modify --> Auto Enhance Audio
3. Right window, click on Audio Enhancements for any problems

Noise Reduction

1. Select the audio clip
2. Click the wizard inspector
3. Select audio enhancements
4. Background noise removal and hum removal to remove noise

Refer Enhance Audio section in the Help window of FCP.

Preroll

1. Import both videos
2. Drop the title video into the TL and then the video to be processed.

Exporting the Edited Video

1. File --> Share --> Master File

This will export the video in quick-time format.



Recovering from Mistakes

Undo : Command+Z

Thursday, July 17, 2014

Using Figoro Gem with Moonshine

1. Add gem 'figaro' to Gemfile

2. rails g figaro:install

Creates config/application.yml and adds it to .gitignore.

3. Here is the syntax for environment specific configuration

# config/application.yml

pusher_app_id: "2954"
pusher_key: "7381a978f7dd7f9a1117"
pusher_secret: "abdc3b896a0ffb85d373"
google_analytics_key: "UA-35722661-5"

test:
  pusher_app_id: "5112"
  pusher_key: "ad69caf9a44dcac1fb28"
  pusher_secret: "83ca7aa160fedaf3b350"
test:
  google_analytics_key: ~
 
4. Use rake secret to generate a secret for any of your keys

5. Access the values in the code:

 ENV['pusher_secret']

 or

 Figaro.env.pusher_secret

6. Specify required keys in config/initializers/figaro.rb

Figaro.require("pusher_app_id", "pusher_key", "pusher_secret")

7. Add config/application.yml to local directive in Moonshine. Edit moonshine.yml :shared_config: directive.

8. Deploy the application



Monday, July 14, 2014

How to create .ruby-version and .ruby-gemset in a Rails 4.1 project

$rvm use ruby-2.1.2
Using /Users/bparanj/.rvm/gems/ruby-2.1.2
~/projects/openbay $rvm gemset use openbay
Using ruby-2.1.2 with gemset openbay
$cat .ruby-version
cat: .ruby-version: No such file or directory
$rvm --ruby-version use 2.1.2
Using /Users/bparanj/.rvm/gems/ruby-2.1.2
$rvm --ruby-version use 2.1.2@openbay
Using /Users/bparanj/.rvm/gems/ruby-2.1.2 with gemset openbay
.ruby-version is not empty, moving aside to preserve.
~/projects/openbay $cat .ruby-version
ruby-2.1.2
$cat .ruby-gemset
openbay

Thursday, July 10, 2014

How to get controller and action name in Rails helper method

In Rails 4 :

    params[:controller]
   
    params[:action]






will give you the name of the controller and the name of the action respectively.

Ternary Operator in Ruby

(Some condition) ? true-case-value : false-case-value

Wednesday, July 09, 2014

How to update all packages in Ubuntu 12.04

If you are logged in as root:

$ apt get-update
$ apt get-update dist-upgrade

otherwise run them as sudo.

$ reboot

This will make the changes to be picked up.

Reference:

How to update all packages in Ubuntu 12

Tuesday, July 08, 2014

rvm rvmrc to [.]ruby-version

WTF? What do we need to do to get rid of this BS? From the root of your Rails project, run:

$ rvm rvmrc to .ruby-version

Thursday, June 26, 2014

How to use Ruby 2.1 as the default Ruby in Textmate

1. $ rvm get head
2. $ which rvm-auto-ruby | pbcopy
3. Go to Textmate preferences and Variables tab, add a new variable by clicking the + button. The name of the variable is TM_RUBY and copy the path to the ruby from step 2 as the value.

Wednesday, June 25, 2014

Why using Interactor Gem is a Very Bad Idea

Using interactor gem is a horrible idea. Here are the reasons:

1. It results in anemic classes, classes that don't have any behavior.

Their only purpose is to organize. You can organize using a DSL, something like rspec syntax: organize "Use Case" { specify the sequence of actions to take }. This does not have to be a class, the DSL is just a way wire different classes together.

2. The hash that gets passed around is nothing but a glorified global variable.

If you apply Domain Driven Design, you will use application specific data types instead of built-in data structures. This makes the concepts of your domain explicit. You can achieve 'Ubiquitous Language' in your team.

3. This results in "Hash Oriented Programming" not OO.

4. Failures are silent, which means there is no clear transparency into the system.

5. Class names are verbs. Are you kidding me? Why do you want to ignore the basics of good OO design?

What is the alternative then? Learn about Hexagonal Architecture and Domain Driven Design. Apply those principles religiously. When you apply these good design principles, your use cases become the core of your application which is not dependent on any technology. They become testable and compose able. It's like legos that gives you basic building blocks that can be combined in different ways to be used in different external and internal adapters.





Creating Paper Prototype to Design a Web Page

If you are getting lost in details and overwhelmed by the amount of data you have to deal with, this post will bring some sanity to your webpage design process.

Tools Required

Wall pads, scissors, colored pens, tape

What to Do

1. Buy a Post-it-Self-Stick-Wall-Pads from any office supply store.
2. Get all of your notes and lay them out into the big ass paper.
3. Arrange and categorize the notes into sections.

Structure

Focus on structure and copy existing design of a website that you like. In this phase you only worry about where different elements go in the layout. For instance, where does the screenshot of a feature go? Where does the headline and paragraphs go?

You can take screenshots of a website that you like and use Skitch to label different elements on the page. These labels could be just numbers. You can also blur or strike-out elements you don't want in your design in this phase.

You have to let your structure evolve over time by letting it marinate. Post it on the wall where you can look at it everyday and make quick corrections using red pen, using small sticky notes and pasting over the existing structure to note down some notes for yourself. Things does not have to be perfect the first time. The draft version can be approximate. It will be refined by revising it over a period of one to two weeks.

Content

Write down the content is smaller size paper and you can start pasting them over the existing structure.

Form

In this phase you focus on the font color, font size, font style, background grid colors etc. You make it more real.

Conclusion

This allows you to reduce confusion and clarify ideas before you can handover your design to a graphic designer. You can get a PSD file and hand it over to a front-end developer to create the HTML and CSS for the web page.

Saturday, June 21, 2014

Godel : Consistency or Complete

Less software as a design technique, not a goal. Thinking about decisions as potential energy vs kinetic energy. Decisions take energy and creates stress. It uses mental processing power.

Defer decision as much as possible

1. Estimating work.
2. Pure development time vs Fighting fires
3. Premature speculation (promises)
4. Requirement vs Schecule (out of sync)
5. Not planning for change.

Wednesday, June 11, 2014

Hello Docker 1.0

1. Download boot2docker osx-installer
2. Install it.
3. Check version
     $ docker -v
     Docker version 1.0.0, build 63fe64c
4. Upgrade VM and start docker
$ boot2docker stop
$ boot2docker download
$ boot2docker start

  $ docker run ubuntu echo hello world

 Unable to find image 'ubuntu' locally
 Pulling repository ubuntu
 ad892dd21d60: Download complete
 511136ea3c5a: Download complete
 e465fff03bce: Download complete
 23f361102fae: Download complete
 9db365ecbcbb: Download complete
 hello world

 $ docker run ubuntu echo hello world
  hello world

Sunday, June 08, 2014

Ruby Science Code Review

This article is a discussion of the chapter on Replace Conditional with Null Object. Null object does not solve any problems in most cases. For instance here is the sample code from the book:

if user.nil?
  nil
else
  user.name
end

If I cannot use Null Object (which creates unnecessary small objects). What is the right way to fix this? You need to apply the basics of Object Oriented Programming.  Ask yourself:


  • What does it mean to have a user variable with nil value?
  • If user does not exist in our system what do you want to display instead of their name? 
  • Is blank value acceptable in this case?


 If the above code snippet is part of a method, then the precondition for the method is that user object cannot be nil. It is a contract between the client and the API. As l long as I provide a valid user the method will be able to do it's job (fulfill the contract in Design by Contract terminology) and provide me the name. It's the responsibility of the client code to provide the method a valid user. In this case the solution would be:

Client Code

if user.nil?
  'User not found'
else
   user_name_for(user)
end

API

def user_name_for(user)
  user.name
end

Ideally I would look for the ActiveRecord call that throws an exception instead of returning nil for a record that is not found. I would handle the ActiveRecord::NotFound exception and translate it to business specific exception like MyApp::UserNotFound class that takes the message indicating the context of the application as the exception message. So there would be no nil check required in this case.

Sunday, June 01, 2014

Ruby Science Book Notes

Code Reviews

1. Use git diff and --patch to examine code before commit.
2. Push your feature branch and invite your teammates to review the changes via git diff origin/master..HEAD
3. Share your best refactoring ideas with them.
4. Refactor for readability first.

Metrics

1. Flog : Detect complexity

Example :
$ flog app lib

flog score of 10 or higher : Method may be too long
A class with a flog score of 50 is a large class that might need refactoring.

$ flog -a app/models/question.rb

2. Flay : Find duplication
3. Reek : Find bad code
4. Churn : Find files with high churn rate
5. MetricFu : Analyze application

Take a look at Code Climate.


Tuesday, May 27, 2014

Upgrading Ruby to 2.1.2 with Moonshine

I was able to upgrade Ruby to 2.1.2. Since I am using Rails 3, I upgraded Moonshine by running:

script/rails plugin install git://github.com/railsmachine/moonshine.git --force

I did not run 
 
script/rails generate moonshine

I am retaining the old generated files.

WARNING: Nokogiri was built against LibXML version 2.8.0, but has dynamically loaded 2.7.6

I had to run: 

sudo gem install nokogiri --   --with-xml2-include=/usr/include/libxml2   --with-xml2-lib=/usr/lib   --with-xslt-include=/usr/include/libxslt   --with-xslt-lib=/usr/lib
 
on the server from the directory:
 
/usr/lib/ruby/gems/2.1.0/gems
 
Note: This server is managed by Moonshine. I could not get rid of this warning any other way.
 
Reference:
 
How to fix Nokogiri on Ubuntu 

Getting mate command to work on Mavericks

After trying different suggestions from superuser.com on how to setup the shortcut, I had to define an alias in ~/.bash_profile as a workaround:
alias mate='/Applications/TextMate.app/Contents/Resources/mate '

Monday, May 26, 2014

Migrating from Github to Bitbucket

1. git remote show origin or git config --get remote.origin.url
2. git remote add origin ssh://git@bitbucket.org/your-user-id/your-project.git
3. Add the ssh key of the server to bitbucket SSH keys.
4. Login to the server and from the rails project current directory change the git remote by running the command in step 2.

Since I am using Moonshine, I had to delete the cached-copy folder on the server. Because it points to github and creates problem when cap deploy is run.

Monday, April 21, 2014

Essential Skills for TDD Terminology

Domain

A specified sphere of activity or knowledge. Example : Visual communication is the domain of the graphic designers.

Visual Communication
 - Contour
 - Contrast
 - Opacity
 - Form

Finance
 - Equity
 - Debt
 - Gross Margin
 - Net Income

Math
 - Parallel
 - Ordinate
 - Arc
 - Angle

Problem Domain

Problem domain refers to real-world things and concepts related to the problem.

Problem Domain Analysis

Problem Domain Analysis is the process of creating a mental model that describes the problem. The focus is on understanding the problem domain.

Solution Domain 

Solution Domain refers to real-world things and concepts related to the solution.

Solution Domain Analysis

Solution Domain Analysis is the process of arriving at a solution. It describes the sequence of steps used to solve a given problem. Finding abstractions helps us to solve problems.

Tuesday, April 08, 2014

Destroy All Software - Episode Fast Tests With and Without Rails Review

The specs in the final solution abuses mock by mocking the ActiveRecord API. The expectation mocks update_attributes. He says the solution only depends on RSpec and specs run outside of Rails, so the specs run fast. The problem is that the dependency on Rails exists because of the coupling created by the mocking of ActiveRecord. The tests are now brittle and can break when you upgrade Rails if the active record API changes.

Monday, April 07, 2014

Growing a Test Suite Screencast Review

This is the review of the solution discussed in Growing a Test Suite Screencast.

Here is a list of things that the solution violates:

1. Separate Command from Query.
     digest method is a command. digest method should not return any value
2. Allocate responsibilities to the right class.
    digest method does not belong to the Cheese class.
3. Law of Demeter.

Here is my solution:

class Walrus
  attr_reader :energy
 
  def initialize
    @energy = 0
  end
 
  def eat(food)
    digest
    @energy += food.energy
  end
 
  private
 
  def digest
    p 'Digesting...'
  end
end

class Cheese
  def energy
    100
  end
end


cheese = Cheese.new
w  = Walrus.new

p "Energy before eating is : #{w.energy}"

w.eat(cheese)

p "Energy now is : #{w.energy}"

Friday, March 28, 2014

Checking if a number is prime in Ruby

Go to irb :

 > require 'prime'
 => true
 > Prime.prime?(2)
 => true
 > Prime.prime?(3)
 => true
 > Prime.prime?(10)
 => false

Wednesday, March 26, 2014

Configuring Guard to Display output in Red Green Colors

Change the Guard file guard method to:

guard :rspec, cmd: 'rspec --color --format doc' do
... contents unchanged

end

From the root of the project run: guard
You will now see the colors in the terminal whenever the test is run.

Friday, March 21, 2014

Alternative to using take and drop methods in Array class

The take method takes elements from the beginning whereas the drop takes the elements from the end of the array. These methods require some mental mapping of the method names to what it does. I was thinking about reducing this gap. Here is the experiment in the IRB:

2.0.0 > a = [1,2,3,4]
 => [1, 2, 3, 4]
2.0.0 > a.first(2)
 => [1, 2]
2.0.0 > a
 => [1, 2, 3, 4]
2.0.0 > a.last(2)
 => [3, 4]
2.0.0 > a
 => [1, 2, 3, 4]

It just works! This is one of the reason why I love Ruby.

Monday, March 17, 2014

How to count number of files in a bucket in S3 recursively

1. git clone https://github.com/s3tools/s3cmd
2. cd s3cmd
3. s3cmd --configure
Enter the Amazon credentials.
4. ./s3cmd ls --recursive s3://your-bucket/another-bucket/foo

This will recursively find all the folders under foo and list all the files.

5. You can pipe it to wc to get the number of files like this :
     ./s3cmd ls --recursive s3://your-bucket/another-bucket/foo | wc -l

   

Loading rubyzip gem in irb

LoadError: cannot load such file -- rubyzip

Instead of : require 'rubyzip' use require 'zip'

Turn off Bonjour Notifications in Cyberduck


On Mac OS, run the following command in a terminal:

defaults write ch.sudo.cyberduck rendezvous.enable false

Reference:

Diable Bonjour in Cyberduck

Using MIME types outside of Rails 4

In a IRB session:

require 'action_dispatch/http/mime_type.rb'
 => true
> MIME::Types.type_for('a.pdf')

Thursday, February 20, 2014

SimpleDelegator in Ruby

require 'delegate'

class User
  def born_on
    'July 21'
  end
end

class UserDecorator < SimpleDelegator
  def birth_year
    born_on
  end
end

decorated_user = UserDecorator.new(User.new)
p decorated_user.birth_year  #=> July 21

Friday, February 14, 2014

psych.rb in `parse': found a tab character that violate intendation while scanning a plain scalar at

You will not be able to go the rails console. Go to the root directory of the rails project and fire up an irb session:

1. require 'yaml'
2. YAML::ENGINE.yamler = 'psych'
3. YAML.load_file('config/your-config-file.yml')

Autocorrect yaml file syntax errors: s.gsub!(/\t/, ' ')

This will reproduce the problem. See the line number of row to find the syntax error. Fix it by changing the tab to space.

Wednesday, January 15, 2014

RVM is not a function, selecting rubies with 'rvm use ...' will not work.

To fix this in Ubuntu 12.04, go to : Profile --> Preferences, Title and Command tab and check the box for 'Run command as a login shell'

Installing RVM on Ubuntu 12.04

1. sudo apt-get install curl
2. \curl -L https://get.rvm.io | bash -s stable
3. source ~/.rvm/scripts/rvm

Do not run OS updates in parallel when installing RVM.



Reference:
Install Ruby on Rails on Ubuntu 12.04

how to setup Textmate 2 to run mate from command line

Go to preferences --> Terminal and click 'Install' to install shell support.

If you get the error 'To open a bundled gem, set $EDITOR or $BUNDLER_EDITOR'
Add the following line to ~/.bash_profile:

export BUNDLER_EDITOR=mate

Tuesday, January 14, 2014

Setup Textmate 2 to use RVM

1. $ which rvm-auto-ruby
2. Add the following to ~/.tm_properties

TM_RUBY="/path/to/rvm-auto-ruby/from/step1/"

3. Restart Textmate 2
4. Run : puts RUBY_VERSION as a ruby file.