Thursday, May 02, 2013

How to select the non highlighted button in the popup window on Mac OS

Go to Preferences -> Keyboard. At the bottom, turn on "All controls" under "Full Keyboard Access". Hit space to activate the secondary button.

Friday, April 26, 2013

Thursday, April 25, 2013

How to store array in mysql database in a Rails project


1. The column type should be text
2. serialize the column. In the active record class : serialize :your_field
3. Book.new(:your_field => [1,2])

Monday, April 22, 2013

Correction to Example in Ruby Programming Language


In Ruby 2.0, I had to make changes to the given code in the book:

birthyear = 1975

generation = case birthyear
    when 1946..1963 then "Baby Boomer"
    when 1964..1976
      "Generation X"
    when 1978..2000
      "Generation Y"
    else nil
    end

p generation

Thursday, April 18, 2013

How to use VCR, Webmock with RSpec


1. Add the gems to the Gemfile under test group:
gem "webmock"
gem "vcr"

2. bundle

3. require 'vcr' as the first line in spec_helper.rb

4. Add

VCR.configure do |c|
  c.cassette_library_dir = 'spec/fixtures/cassettes'
  c.hook_into :webmock
  c.ignore_localhost = false
  c.allow_http_connections_when_no_cassette = true
end

inside the configure block.

5. Add WebMock.allow_net_connect! in the before block in the specs.
6. Wrap your network calls using :
       VCR.use_cassette do
              controller code that accesses network goes here
        end

Friday, April 12, 2013

Two different ways to execute a block

It is familiar that you will see yield being used when the block is anonymous and block.call being used when the block is explicit in the list of parameters for the method. Actually, you can use yield even when the block is explicitly passed to the method:

def foo(&block)
  yield
  block.call
end

foo { puts 'hi hey again' }

Tuesday, April 02, 2013

Setting two spaces as the default in Sublime Text 2


{
    "tab_size": 2,
    "translate_tabs_to_spaces": true
}

Save this in the Preferences -> Settings - Default file.

Installing Guest Additions on Ubuntu 12.04

1. sudo apt-get install virtualbox-guest-additions-iso
2. Boot the guest OS inside Virtualbox
3. In the virtual box menu, use Devices -> Install Guest Additions.

Reference: ubuntuforums.org

Monday, April 01, 2013

uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

This happens when creating a new project in Rails 2.3.8 if the Ruby gems version is 1.8.24.
Solution:
gem update --system 1.5.3
 
Now, rails blog will create a new project. 

program rails is not installed ubuntu rvm rails 2.3.8

1. Type : gem env, look at the  EXECUTABLE DIRECTORY value

2. Add the path to that directory to ~/.bashrc:
PATH="${PATH}:/home/your-user-name/.rvm/gems/ruby-1.8.7-p299/bin"


3. Open a new terminal

4. Type : rails -v



You will now see that rails command is recognized.

Friday, March 29, 2013

How to configure Sublime Text 2 to use Ruby 2.0 using RVM

{ "env":{ "PATH":"${HOME}/.rvm/bin:${PATH}" }, "cmd": ["rvm-auto-ruby", "$file"], "file_regex": "^(...*?):([0-9]*):?([0-9]*)", "selector": "source.ruby" }

Copy this file to your rvm.sublime.build file.

For more info: Sublime Text 2 Integration With RVM and Rspec: Take Number 2

Monday, March 25, 2013

How to configure rspec to test controller macros


Include the line:
  config.include OnboardingControllerMacros, :type => :controller
in spec_helper.rb

Monday, March 18, 2013

Readline was unable to be required, if you need completion or history install readline then reinstall the ruby.

This happens on Ubuntu 12 when installing Ruby 2.0 using RVM. To fix this follow the instructions below:

If you're using Ubuntu 12.04, DO NOT pkg install readline, with or without --skip-autoreconf. After you've done that, either readline or zlib will be broken no matter what combination of switches you give to rvm install ruby-2.0.0-p0 .
To get it to work, do the apt-get install that rvm requirements tells you to do, do a rvm pkg uninstall readline and then do a simple rvm remove ruby-2.0.0-p0; rvm install ruby-2.0.0-p0

Now the irb should work fine without any warnings. 

 http://stackoverflow.com/questions/8176076/how-to-get-readline-support-in-irb-using-rvm-on-ubuntu-11-10

Tuesday, March 12, 2013

iPhone 5 cord stuck in USB Port

You can easily remove your iPhone 5 cable stuck in USB port by using either your shirt collar stays or a toothpick. Just stick it inside the USB port, sitting on top of the cable and pull them together.

Monday, February 25, 2013

Accessing Git Repository on Github


Problem:
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Solution:

Password Caching (Explains how to use https to access repository and cache password so you don't get annoying password prompt whenever you have to access the github repo)

1. curl -s -O \
  http://github-media-downloads.s3.amazonaws.com/osx/git-credential-osxkeychain
chmod u+x git-credential-osxkeychainsudo mv git-credential-osxkeychain `dirname \`which git\``
git config --global credential.helper osxkeychain

Using Bundler Outside Rails

1. bundle init
2. Open Gemfile and add your gems : gem 'highline'
3. bundle

Bundler without Rails

Friday, February 22, 2013

Using Phusion Passenger as a Rails Server on Mac OS X 10.7.5

Software used : RVM Passenger 3.0 on Mac OS X 10.7.5

1. rvm use 1.9.3
2. gem install passenger
3. rvm get head
4. rvm reload
5. rvm repair all
6. passenger-install-apache2-module

Thursday, February 21, 2013

Could not find gem 'activerecord-sqlite3-adapter (>= 0) ruby' in the gems available on this machine.

Instead of
gem install activerecord-sqlite3-adapter
run
gem install sqlite3

Archimedes and the Internet

If Archimedes was born in this era, he would say:

Give me a single email account, and a website, and I will move the Internet.

Saturday, February 16, 2013

Playing with URL Helpers in Rails 3.2 Console


 :001 > Rails.application.routes
 => # 
 :002 > Rails.application.routes.url_helpers
 => # 
 :003 > Rails.application.routes.url_helpers.permissions_get_access_token_url
ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true
 :004 > Rails.application.routes.url_helpers.permissions_get_access_token_path
 => "/permissions/get_access_token"
 :005 > Rails.application.routes.url_helpers.permissions_get_access_token_path(:host => 'http://localhost')
 => "/permissions/get_access_token"
 :006 > Rails.application.routes.url_helpers.permissions_get_access_token_url(:host => 'http://localhost')
 => "http://http://localhost/permissions/get_access_token"
 :007 > Rails.application.routes.url_helpers.permissions_get_access_token_url(:host => 'localhost')
 => "http://localhost/permissions/get_access_token"
 :008 > Rails.application.routes.url_helpers.permissions_get_access_token_url(:host => 'localhost:3000')
 => "http://localhost:3000/permissions/get_access_token"

 or

  :001 > include ActionDispatch::Routing
  => Object
  :002 > include Rails.application.routes.url_helpers
  => Object
  :003 > permissions_path
  => "/permissions"
  :004 > permissions_url
 ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true
  from /Users/bparanj/.r

Reference:
Recognizing URL Helpers

Friday, February 15, 2013

protocol version mismatch (client 7, server 6) tmux

ps aux | grep tmux

Look at the second column for the process id. Then run : kill process-id-for-tmux

Sunday, February 10, 2013

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

1. Install GCC Installer https://github.com/kennethreitz/osx-gcc-installer
2.

rvm remove 1.9.3
brew install openssl
rvm install 1.9.3 --with-openssl-dir=`brew --prefix openssl`


# Install openssl
echo "Install openssl..."
brew install openssl
brew link openssl
# download cert.pem file for openssl
cd /usr/local/etc/openssl/certs/
sudo curl -O http://curl.haxx.se/ca/cacert.pem
sudo mv cacert.pem cert.pem
cd -
echo "
# cert.pem file for openssl 
export SSL_CERT_FILE=/usr/local/etc/openssl/certs/cert.pem" >> ~/.bash_profile
source ~/.bash_profile

Shell script to turn your laptop to a development machine.

Saturday, February 09, 2013

PayPal Application id for Sand Box

Use APP-80W284485P519543T as the app_id

This is the same for all sandbox users and any PayPal API (Adaptive Payments, Express Checkout etc).

Sunday, February 03, 2013

Convert HAML to ERB


1. rails g install haml2erb
2. Gemfile :
gem 'mixology'
3. bundle
4. Rails console : Haml2Erb.convert('.foo')

This plugin is not perfect. I had to refer HAML documentation to convert some of the lines.

no such file to load -- less Twitter Bootstrap, Rails 3.2.11

1. In Gemfile, for group :assets block, add:
        gem "less-rails"
2. Add to Gemfile (not in any block), add:
         gem 'therubyracer', :require => 'v8'
3. bundle

It will now work.

Thursday, January 31, 2013

rake aborted! can't convert nil into Hash


Solution Source:
Rails 3.1, rake 0.9.2.2, add this code on config/boot.rb
require 'yaml'
YAML::ENGINE.yamler = 'syck'

Monday, January 28, 2013

Useful Tools for Testing Web API


1. RSpec HTTP : https://github.com/c42/rspec-http

response.should be_http_ok
response.should be_http_created
response.should be_http_unprocessable_entity
response.should be_http_im_a_teapot
response.should have_header('Content-Type')
response.should have_header('Content-Type' => 'application/json')
response.should have_header('Content-Type' => /json/)

2. JSON Spec : https://github.com/collectiveidea/json_spec

json_spec defines five new RSpec matchers:

be_json_eql
include_json
have_json_path
have_json_type
have_json_size

3. VCR : https://github.com/myronmarston/vcr

Screencast on VCR : http://avdi.org/devblog/2011/04/11/screencast-taping-api-interactions-with-vcr/

Friday, January 25, 2013

'too many connection resets (due to HTTP session not yet started - IOError) after

This happens when you use VCR with Webmock. There is an open bug on Webmock that is causing this problem. The fix is to either downgrade the Webmock to 1.0 version or use Fakeweb.

Thursday, January 24, 2013

Using pry in test environment


Is it possible to use pry when I am running my tests? Sometimes when I am running specs for legacy code, I need a way to experiment with the existing code.


Answering my own question. Yes, it is possible. Just add binding.pry in the production code, run the specs, pry will stop at the line where you have the binding in the terminal window where you have the test running. You can also use pry-nav to use the ruby debug familiar commands step, next and continue while you debug the code.

Installing Ruby 2.0 on Mac OS 10.8.2 using RVM

1. Make sure you have the latest RVM
     rvm get head
     rvm reload


$ brew install autoconf
$ brew install automake
$ brew install libyaml

$ rvm install ruby-head

Stolen from the blog post instructions How to install Ruby 2.0 (ruby-head) with RVM

Creating a New File in a Folder in Textmate 2

Textmate 2 does not have the quick shortcut to create a file from a selected folder. Here is a workaround:

1. Select the folder where you want the new file.
2. Hit Option+Command+N keys to create a new file.
3. Add the content and save the file. It will get saved in the selected folder.

Tuesday, January 22, 2013

To open a bundled gem, set $EDITOR or $BUNDLER_EDITOR


1. bundle open rails
      gives that error.
2. Add :
      export BUNDLER_EDITOR=mate
    to ~/.bash_profile

Thursday, January 17, 2013

How to push branch to remote

To check-in your new branch you created locally : 1. git checkout -b your_branch 2. git push -u origin your_branch

Friday, January 11, 2013

Wednesday, January 09, 2013

Configuring Moonshine to use Apache XSendFile for Rails 3.2


1. rails plugin install git://github.com/railsmachine/moonshine_xsendfile.git
2. In the Moonshine manifest file:
    configure :xsendfile => {:x_send_file_path => '/absolute/path/to/download/url'}
    recipe :xsendfile
   
    This will work even if you have subdirectories under the /are directory.
3. In production.rb, uncomment the line:
    config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache

4. In your controller:
      send_file '/absolute/path/to/download/url/file.pdf', type: 'application/pdf'

Thursday, January 03, 2013

Rails 3.2, Factory Girl


1. Include :
 
    group :development, :test do
 gem 'factory_girl_rails'
end

in Gemfile

2. bundle install
3. create factories.rb under spec folder
4. Add the factory definitions in it :

FactoryGirl.define do
 factory :user do
   email 'elinora@zepho.com'
   password 'welcome'
   primary_paypal_email 'elinora.price@zepho.com'
 end
 # product factory with a belongs_to association for the user
 factory :product do
   name 'TDD Workbook'
   price 49.99
   user
   thanks_page 'www.zepho.com/thanks.html'
   cancel_page 'www.zepho.com/cancel.html'
   sales_page 'www.zepho.com/sales_page.html'
   download_page 'www.zepho.com/download.html'  
 end
end

In this definition I have factory for user has_many :products relationship.
5. Create a support directory and include controller_macros.rb in it:
module ControllerMacros
 def login_user
   @request.env["devise.mapping"] = Devise.mappings[:user]
   user = FactoryGirl.create(:user)
   # user.confirm! # or set a confirmed_at inside the factory. Only necessary if you are using the confirmable module
   sign_in user
 end
end
6. In spec_helper.rb add the devise helpers:
RSpec.configure do |config|
 ...
 config.include Devise::TestHelpers, :type => :controller
 config.include ControllerMacros, :type => :controller
 ...
end
7. In your controller spec, now you can do this:
 
   context 'User is logged in' do
    before do
      login_user
    end

    it 'should render index page' do
      get :index

      response.should be_success
    end
  end
 


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