Monday, December 31, 2012

How to Create DNS Records using Linode API


dns = Fog::DNS.new(provider: 'linode',
                                    linode_api_key: 'your-linode-api-key-goes-here')
zone = dns.zones.create(domain: 'your-domain.com',
                 email: 'admin@your-domain.com')
zone.nameservers

Create a www version of your site and point to the right IP.
record = zone.records.create(value:  '1.2.3.4', name: 'your-domain.com', type: 'A')

To make www.your-domain.com go to the same place, use a cname record:
record = zone.records.create(value: 'your-domain.com', name: 'www', type: 'CNAME')

Thursday, December 13, 2012

to_yaml method y broken in Ruby 1.9


vi ~/.irbrc
YAML::ENGINE.yamler = 'syck'
Save. Now you will be able to use the method y to dump objects in yaml format.

error: The following untracked working tree files would be overwritten by merge: Library/Formula/pbrt.rb



cd /usr/local
git reset --hard origin/master
brew update


Rails 3.2 Tagged Logging

MyLogger = ActiveSupport::BufferedLogger.new(Rails.root.join('log/my_tagged.log'))
MyTaggedLogger.tagged("PAY") { MyTaggedLogger.info "Hello I am working!" }

Wednesday, December 05, 2012

Tuesday, December 04, 2012

Monday, December 03, 2012

How to install local gem


1. Download the .gem file.
2. gem unpack file.gem .
. is the current directory
3. Specify in Gemfile:
   gem 'name-of-gem', '0.1.0', :path => "/path/to/the/unpacked/gem/directory"
4. bundle install

Friday, November 30, 2012

Turn off generating css.sass and js.coffee files


config.generators.stylesheets = false
config.generators.javascripts = false

in application.rb


Wednesday, November 28, 2012

Install Ruby 2.0 Preview 1 on Mac OS

$ brew install libyaml
$ rvm install ruby-2.0.0-preview1 --with-openssl-dir=$HOME/.rvm/usr --verify-downloads 1

Thursday, November 08, 2012

Monday, October 29, 2012

Rails Error: Unable to access log file. Please ensure that


log/development.log exists and is chmod 0666. The log level has been raised to WARN and the output directed to STDERR until the problem is fixed.

Resolution: 

Change the line : config.log_level = Logger::INFO
    to : config.log_level = :info
in development.rb, production.rb etc.

Tuesday, October 23, 2012

constant ActiveSupport::Dependencies::Mutex (NameError)


Problem:
.rvm/gems/ruby-1.8.7-p299@global/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:55: uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

Ruby gems version 1.8.14

Resolution:

Downgrade gems. gem update --system 1.5.3

Friday, October 19, 2012

The following SSH command responded with a non-zero exit status.


Problem:

The following SSH command responded with a non-zero exit status.
Vagrant assumes that this means the command failed!

mount -t vboxsf -o uid=`id -u vagrant`,gid=`id -g vagrant` v-root /vagrant

Resolution:

1. On your Mac:
$ vagrant gem install vagrant-vbguest
Since I installed Vagrant as a package (dmg) otherwise do : gem install vagrant-vbguest
2. vagrant up

The gem will automatically install the update. If VM is already running just do : vagrant halt

Reference:

Automatically download and install VirtualBox guest additions in Vagrant

Move to the end of the file in vi


$ then A

Monday, October 15, 2012

Upgrading GIT on Ubuntu 10.04


  • sudo add-apt-repository ppa:git-core/ppa
  • sudo apt-get update
  • sudo apt-get install git
Notes from stackoverflow. This works.

Thursday, October 04, 2012

Testing Cookies

Notes from Rails Cookbook:

To fully test cookies, you need to test that your application is not only setting the cookies, but also correctly reading them when passed in with a request. To do that create Cookie object and add that to the simulated test Request object, which is setup before every test in the setup method.

Rails cookie tests : https://github.com/rails/rails/blob/master/actionpack/test/dispatch/cookies_test.rb

Securing Your Server by Closing Unnecessary Ports

I am getting rid of Rails Cookbook dead tree copy I bought in 2007. Notes that are valid for any Rails version.

$ netstat -an

will list all network daemons and the ports they are listening on. This will not show you the service name. To find out do:

$ less /etc/services

This will list the service name and the port number it is running. Diable the service based on your Linux flavor and reboot server to make sure it does not get restarted automatically on reboot.

Debugging Rails Applications

Notes from Rails Cookbook. Since the book is based on Rails 1.2 only some of the recipes are still applicable to Rails 3.2.

1. Ruby syntax checker:
     $ ruby -cw test.rb
        w - warn about questionable code
        c - check syntax

       In vim you can check the syntax quickly while editing by doing:
        :w !ruby -cw

2.  Dump environment info in views:
     <%= debug(headers) %>
     <%= debug(params) %>
     <%= debug(request) %>
     <%= debug(response) %>
     <%= debug(session) %>
     <%= debug(request.env) %>

3. Use rails any_object.to_yaml in your controller's action method.

4. Filter development logs:
    logger.warn "### something went wrong: #{obj.inspect}"

    Show only messages beginning with ### :
    $ tail -f log/development.log | grep "^###"

   This tip combined with Tagged logging feature in Rails 3.2 is powerful debugging tool.

5. Use Firebug console tab to inspect the client server interaction when making AJAX calls.

6. Use Live HTTP Headers to inspect HTTP traffic.


Saturday, September 29, 2012

Solving Programming Problems

1. Write down your question.
       This makes you think and clarify your thoughts.
2. Design an experiment to answer that question.
       Keep the variables to a minimum so that you can solve the problem easily.
3. Run the experiment to learn.

Wednesday, August 29, 2012

Eliminating if else statement using Blocks in Ruby


def foo(a)
  if a == 1
    yield
  else
    42
  end
end

The above method customizes by using a block like this:

result = foo(1) do
  98
end

p result

Wednesday, August 22, 2012

How to stop continuous running fan in MacBook Pro

My MacBook Pro with 8 GB 1067 MHz DDR3 RAM and 3.06 GHz Intel Core 2 Duo was running the fan continuously for couple of weeks. To fix it, I ran:

$ top

in the terminal. I found two ruby processes had been running for 160 hours continuously and were taking up 93% of the CPU usage. I killed them by doing:

$ kill -9 [process-id]

As soon as those two stray processes were killed, laptop became quiet again.


How to install tmux 1.6 on Mac OS

I was having difficulty installing the version 1.6, the older 1.4 version was being picked up. The fix:

1. /opt/bin should be in the path. You can append this to your path by editing the ~/.profile file. Mine looks like this:

##
# Your previous /Users/bparanj/.profile file was backed up as /Users/bparanj/.profile.macports-saved_2010-06-07_at_22:52:52
##

# MacPorts Installer addition on 2010-06-07_at_22:52:52: adding an appropriate PATH variable for use with MacPorts.
export PATH=/opt/local/bin:/opt/local/sbin:/opt/bin:$PATH
# Finished adapting your PATH environment variable for use with MacPorts.

export PATH="/usr/local/bin:/usr/local/sbin:/usr/local/mysql/bin:$PATH"

2. curl -OL http://downloads.sourceforge.net/project/levent/libevent/libevent-2.0/libevent-2.0.19-stable.tar.gz

3. tar xzf libevent-2.0.19-stable.tar.gz

4. cd libevent-2.0.19-stable

5. ./configure --prefix=/opt

6. make

7. sudo make install

8. tar xzf tmux-1.6

9. cd tmux-1.6

10. LDFLAGS="-L/opt/lib" CPPFLAGS="-I/opt/include" LIBS="-lresolv" ./configure --prefix=/opt

11. make && sudo make install

12 which tmux 

showed that the older 1.4 version was being picked up from /opt/local/bin, I deleted it by : sudo rm /opt/local/bin/tmux


How to check tmux version

$ tmux -V

Saturday, August 11, 2012

Rails 3.2 Errno::EACCES Permission Denied when uploading files

1. Make sure the directory has the right permission:

   chmod -R 777 uploads

2. The uploads directory is at the same level as app directory. You can change the upload location from the public folder to any folder by customizing the store_dir in your uploader class:


 def store_dir
     "#{Rails.root}/uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

3. You also have to define cache_dir in your uploader class, otherwise it will still throw exception.


  def cache_dir
    "#{Rails.root}/tmp/uploads/cache/#{model.id}"
  end


Monday, July 16, 2012

Error: This transaction cannot be processed due to an invalid merchant configuration.

ActiveMerchant 1.26, Rails 3.2

Resolution:


1. Create your selling test account using the Preconfigured option.
2. Under Account Type, select Website Payments Pro.
3. My Account --> Profile --> API access to get API username, API Password and Signature

Remember the API credentials are different from the test login account. You have to save the login password to the Sandbox account in Step 1 above. There is no way to go back and view the login password to the Sandbox account.

Sunday, July 08, 2012

remove github prompt when checkin

Change the url that has https to :


url = git@github.com:your_github_username/your_project.git

Saturday, June 23, 2012

TDD Screencasts by Kent Beck

1. Test for remove operation does not fail. He writes a test and does not run it, he goes to the implementation and implements. Then he runs the test and it passes.
2. Interesting to see how he uses the debugger to learn about the API and uses that information to write a test.

Wednesday, June 06, 2012

github push is prompting for username and password

I was getting this error for https://github.com/bparanj/mongodb_specs repo. Fix :


$git config remote.origin.url git@github.com:bparanj/mongodb_specs.git

Thursday, May 31, 2012

-bash: mongod: command not found


export PATH=$PATH:/usr/local/mongodb/bin
For Mongodb 2.0.3
mongod --dbpath /Users/bparanj/data/mongodb
The dbpath is the path to the mongodb.config file
which contains :
dbpath=/Users/bparanj/data/mongodb

Deploying to a VPS

To get the http://railscasts.com/episodes/335-deploying-to-a-vps?view=asciicast working I had to do :

1. apt-get install sqlite3 libsqlite3-dev
2. Add : gem 'pg' and gem 'unicorn' to Gemfile

Wednesday, May 30, 2012

undefined local variable or method `autotest' for main:Object

This error happens when you have this : require autotest/fsevent
in your ~/.autotest file, change it to : require 'autotest/fsevent'

Thursday, May 10, 2012

Data Driven Unit Test


How do you avoid loops in your specs?

Like Alex points out, this is a test smell according to Gerard Mezos. In .NET they have something called as data driven unit test. In Ruby we can accomplish the same thing using the following:

  def data_driven_spec(container)
    container.each do |element|
      yield(element)
    end
  end

and in your test you can do :


  it "should return back slash pre-pended to all special characters" do
 
    SPECIAL_CHARACTERS = ["?", "^", "$", "/", "\\", "[", "]", "{", "}", "(", ")", "+", "*", "." ]
 
    data_driven_spec(SPECIAL_CHARACTERS) do |special_character|
      result = Regexpgen::Component.match_this_character(special_character)
      result.should == "\\#{special_character}"    
    end
  end

The code is taken from my regexpgen ruby gem. My test differs from the message that goes in to the it method. I have raised the level of abstraction, whereas Alex substitues the a variable to vary the message.

Wednesday, May 09, 2012

`bin_path': can't find gem rspec-core

use rspec instead spec for running the spec file.

Creating a Ruby gem with RSpec as the test framework

1. bundle gem 'your-gem-name'
2. Run : rspec --init from your gem directory to generate the spec/spec_helper.rb and .rspec files.

.rspec has the configuration such as color and format of the output when specs are run.


Tuesday, May 01, 2012

irb tricks

1. touch ~/.irbrc
2. Edit the .irbrc and add the following code:


require 'pp'
require 'rubygems'

class Object
  def ls
    %x{ls}.split("\n")
  end
 
  def pwd
    Dir.pwd
  end
 
  def cd(dir)
    Dir.chdir(dir)
    pwd
  end
end

alias p pp

3. Now whenever you open an irb session you can now list the directory contents by doing ls, print working directory by pwd and change directory by doing cd "directory-name".

Friday, April 27, 2012

Solution for Ruby Koans

You can download by solution from here https://github.com/bparanj/ruby-koans-edgecase.

This took me 5.5 hours to complete. I broke this down into 11, 30 minutes sessions over a period of two weeks.

Things that I learned:

1. It was a "aha" moment when I worked through a series of tests that described the behavior of a class. You have to do the exercises to get the feel for describing the behavior or specification of a class.
2. It helps you to find your strengths and weakness so you will know where to focus your learning efforts.

How to install rubygems from source on Ubuntu 10.04

1. wget http://rubyforge.org/frs/download.php/69365/rubygems-1.3.6.tgz
2. Extract : tar xvzf rubygems-1.3.6.tgz
3. cd to rubygems directory and run : ruby setup.rb
4. sudo ln -s /usr/bin/gem1.8 /usr/bin/gem


Check version by either : gem -v or gem env

`merge': can't convert String into Hash

This error happens when you have syntax error in your .gemrc file. Fix it. gem env will work again.

How to install Ruby 1.8.7 on Ubuntu 10.04

sudo aptitude install ruby1.8-dev ruby1.8 irb1.8 libreadline-ruby1.8 libruby1.8 libopenssl

sudo ln -s /usr/bin/irb1.8 /usr/bin/irb
sudo ln -s /usr/bin/ruby1.8 /usr/bin/ruby
 
Check the Ruby version : 
 
ruby -v 


How to count the number of files in a given directory in Unix

ls -f | wc -l

undefined method `name' for RubyToken::TkLPAREN

I got that error message when I installed httpclient on Ubuntu 10.04. The gem got installed the error is due to the rdoc. You can turn off the installation of rdoc by appending no rdoc switch to the .gemrc file :

echo 'gem: --no-ri --no-rdoc' >> ~/.gemrc

The above command will append the 'gem: --no-ri --no-rdoc' to your .gemrc file.


How to remove Open JDK on Ubuntu 10.04

sudo apt-get purge openjdk-\* icedtea-\* icedtea6-\*

How to append to a file in Ruby


    my_file = File.open('file_name', 'a')

Once you open the file in append mode, you can write to it. It will get appended to existing contents of the file.

How to list all files with a given extension in Ruby

Dir["*.xml"].each do {|f| p f}

Dir will return all xml files as an array. The block prints the name of the xml file.

How to list all files in a directory in Ruby

Dir.foreach(".") do {|f| p f}

This will print all the file names in the current directory including files that begin with a period.

How to copy local file to a remote Ubuntu server

 scp -i ./your-key.ssh foo.rb user-name@101.101.101.101:.

Where your-key.ssh and foo.rb are in the directory where you are running scp. Since you have . after : at the end of ip address, the local file foo.rb will get copied to the root directory of your remote machine.

How to comment multiple lines in Ruby

Use:
=begin
your code goes here
on multiple lines
=end

multiline comments

How to compare Time in RSpec


When you are dealing with Time the == operator will not pass the test when you compare the time objects. Quick fix is to call to_s and use == to compare the time string values. Like this:

my_timestamp.to_s.should eq("Mon Apr 09 20:56:25 UTC 2012")

Reference:

Comparing time in rspec

Monday, April 23, 2012

no such file to load -- zlib

1. Go to the directory where you extracted the Ruby package:
    Ex : cd ~/temp/ruby-1.8.7-p248/ext/zlib
2. ruby extconf.rb
3. sudo make && sudo make install

Tuesday, April 17, 2012

How to list files in MB on Linux

ls -l --block-size=1M

How to limit the number of records returned by mysqldump

How to restrict the size of mysqldump?

mysqldump --where="true LIMIT 1000" -u user-name -p db-name > exported-data.sql

How to list all the loaded gems on a server

Open a Rails console and type:

 $:.each do |x|
   p x
 end;
 p "hi"

$: variable contains the list of all gems loaded into the system. I am suppressing the output of array of those gems by doing ; p "hi" after the end.

sh: irb: not found

On Ubuntu you need to install irb :

sudo apt-get install irb

no such file to > load -- net/https when starting Rails server

Install libopenssl-ruby1.8.

Monday, April 16, 2012

How to convert ppk file to normal ssh key in Ubuntu 10.04

sudo apt-get install putty-tools
puttygen your_file.ppk -O private-openssh -o new_file_name

scp permission denied publickey

How to copy a file from a remote Ubuntu server to your machine using scp and private key


scp -i /path/to/your_private_key_file user@your_host_or_ip:/path/on/the/remote/machine/file_name .

This will copy file_name to current directory in your local machine

no such file to load -- net/https on Ubuntu 10.04

sudo apt-get install libopenssl-ruby

How to install mysql gem on Ubuntu 10.04

sudo apt-get install mysql-server mysql-client
sudo apt-get install libmysql-ruby libmysqlclient-dev
sudo gem install mysql
Install mysql database connector by running the above commands.

How to install Nokogiri on Ubuntu

libxml2 is missing error message is due to missing libraries. Install the pre-requisite library with:


sudo apt-get install libxslt-dev libxml2-dev

How to install curb gem on Ubuntu 10.04

sudo apt-get install libcurl3 libcurl3-gnutls libcurl4-openssl-dev

How to install bson_ext on Ubuntu 10.04

Using Bundler 1.1.3 for some reason does not work. Solution:

sudo gem install bson_ext -v=1.0.1

installs the gem.

How to ssh using a given private key

ssh -i /path/to/your_private_key_file user-name@your-ip-address-here

Friday, April 13, 2012

It is recommended that your private key files are NOT accessible by others

I was getting this error : Permissions 0644 for '/home/bparanj/Downloads/my-file.ssh' are too open.
when I was ssh ing into a box.
 
Solution:
sudo chmod 600 your-private-key.ssh

Monday, April 09, 2012

Rails Recipes 3rd Edition

The recipe: Focus Your Tests with Mocking and Stubbing show how to use stubs and mocks. It violates one of the testing best practices. DO NOT mock external services. Why? Because you cannot drive the design of a third party library. For a good discussion on this topic read the "Growing Object Oriented Software Guided by Tests".

I scanned through the book, I was a bit disappointed. Lot of the recipes are just from the old book.

Tuesday, March 13, 2012

Using Stubs with Test Spy in Ruby

While I was working on my super stealth product of my company - Affiliate Tracking system, I came across a problem during testing. I had to test the cookie setting logic of my controllers. It was straightforward to test that the cookie was set for the happy path. For the alternative scenario it became tricky to test because RSpec and Rails framework did not play that well together. I even read Devise Rails plugin code to see how Jose Valim handled cookie related problems during testing. No luck. One solution I found was on Stackoverflow. How do I test cookie expiry?


# app/controllers/widget_controller.rb
...
def index
    cookies[:expiring_cookie] = { :value   => 'All that we see or seem...', 
                                  :expires => 1.hour.from_now }
end
...
# spec/controllers/widget_controller_spec.rb
...
it "sets the cookie" do
  get :index
  response.cookies['expiring_cookie'].should eq('All that we see or seem...')
                                               # is but a dream within a dream.
                                               #                - Edgar Allan Poe
end

it "sets the cookie expiration" do
  stub_cookie_jar = HashWithIndifferentAccess.new
  controller.stub(:cookies) { stub_cookie_jar }

  get :index
  expiring_cookie = stub_cookie_jar['expiring_cookie']
  expiring_cookie[:expires].to_i.should be_within(1).of(1.hour.from_now.to_i)
end

This technique is a great example of Test Spy described in Gerard Mezos book xUnit Test Patterns. Basically, you install a spy and check the results collected by the test spy in the verification phase. In this case the Hash is the Test Spy that collects data. See how the stub is used to install the spy in the SUT? It overcomes the problems and isolates the SUT from the Rails framework and allows the code to be tested easily.

In my TDD bootcamps, the topic on Stubs and Mocks generates lot of discussion. To clear confusion that surrounds the stubs and mocks, I would state : Read Martin Fowler's paper on Mocks Aren't Stubs, Stub can never fail your test, only mocks can fail your test. Using stubs in combination with a spy like this makes stubs seem like they can in fact fail your test. But only the data collected by the Test Spy decides whether the test passes or not. So the stub's main purpose is to just isolate the production code from Rails framework and allow access to the internal state of the SUT where there is no direct way to access it.