Saturday, September 14, 2013

How to customize Rails 404, 422, 500 pages that is compatible with Exception Notifier Plugin

1. Add :
            config.exceptions_app = self.routes
to application.rb.
2. Add routes for error pages :
  match '/404', :to => 'errors#not_found'
  match '/422', :to => 'errors#server_error'
  match '/500', :to => 'errors#server_error'
3. Create a errors controller:
     rails g controller errors not_found server_error
4. Implement the actions :

class ErrorsController < ApplicationController
  def not_found
    render :status => 404, :formats => [:html]
  end

  def server_error
    render :status => 500, :formats => [:html]
  end
end

5. Customize the views, not_found.html.erb and server_error.html.erb.

Tuesday, September 10, 2013

Updates were rejected because a pushed branch tip is behind its remote

If you are working on a branch and it gives you this error message when you do a git push, you need to run:
git pull origin master

and now the git push will work. This happens when the master changes and you have not updated the local copy with the changes in the remote master branch.

Sunday, September 08, 2013

Clearing Stuck Delayed Jobs

Delayed job had completed its work, for some reason it was still stuck in the queue. To remove it from the queue, on the server run the commands:

Step 1 :

$ RAILS_ENV=production script/delayed_job stop

This will stop the delayed_job process.

Step 2 :

$ pgrep -f delayed_job

This will return no result, therefore confirming that the delayed_job process has been stopped.

Step 3:

Go to rails console in production and run :

> job = Delayed::Job.count
   (0.3ms)  SELECT COUNT(*) FROM `delayed_jobs`
=> 1

> job = Delayed::Job.first
  Delayed::Backend::ActiveRecord::Job Load (0.5ms)  SELECT `delayed_jobs`.* FROM `delayed_jobs` LIMIT 1
=> #
> job.delete

Thursday, September 05, 2013

Disable Edit and Delete in Rails Admin

Add the following code to rails_admin.rb:


  RailsAdmin.config do |config|
    config.actions do
      # root actions
      dashboard                     # mandatory
      # collection actions
      index                         # mandatory
      new
      export
      history_index
      # member actions
      show
      history_show
      show_in_app
    end
  end

As you can see from above, there is no edit or delete actions defined. Now you will not be able to edit or delete the models when you are logged in as admin.
Due to Kaminari and Will Paginate conflict in Rails Admin, to fix this add the following code to kaminari.rb in config/initializers:

config.page_method_name = :per_page_kaminari

Monday, September 02, 2013

How to find ruby gems

1. Look at the Gemfile.lock and see the dependencies of a gem. Search in github for each gem in the dependency tree to learn more about the gem. You can also use the gem command :
    gem dependency gem_name to get a list of dependencies of a gem. For instance, running :
 
    $ gem dependency capistrano

   Gives the following output:

Gem capistrano-2.15.5
  highline (>= 0)
  mocha (= 0.9.12, development)
  net-scp (>= 1.0.0)
  net-sftp (>= 2.0.0)
  net-ssh (>= 2.0.14)
  net-ssh-gateway (>= 1.1.0)

2. Follow the Rails Core Team members Twitter feed.
3. Talk to other developers and ask what gems they have used in their projects.
4. Subscribe to Ruby podcasts, blogs.

I was working on a Rails project that was having a giant if-else statements to recognize the mime-types of a given file for uploading to Amazon S3. I was looking at Gemfile.lock and used tip #1 above to find the mime-types and read more about the gem on github. I was able to replace my custom mime-type recognition code with the mime-types gem. If you run:

$ gem dependency mime-types

you will see only development dependencies on other gems, there are no runtime dependency on any other gems. This gem is self-contained and is a good unit of reuse.

It's like using small Unix utility to compose and solve many different problems. The only dependency it might have is that it works only on certain versions of Ruby.

Things to Consider When Evaluating Gems

1. Simplicity vs Flexibility

     There is a trade-off between simplicity and flexibility. For instance for file uploading you could use many gems like fog, carrierwave etc and create lot dependencies in your code that provides ease of switching between libraries - flexibility. But it complicates your codebase and simplicity is lost. You will also have more work during upgrade of your project because of these dependencies.

2. Usefulness

     Can I write this by myself in a simpler way that is easier to manage? Read the source code of the gem to make your own decision about reuse or develop on your own.

3. Support and Maintenance
  •     Is there any critical bugs that is not being addressed by anyone? 
  •     Is the source code easy to read and modify for your needs? 
  •     Are the developers active and keep up with upgrading the gem as new Ruby versions are released?

Tuesday, August 06, 2013

Sunday, July 21, 2013

Three Rules of TDD

Notes from Bob Martin's screencast:

1. Write the test first.
2. Write only enough of a test to demonstrate a failure.
3. Write only enough of production code to pass the test.

Friday, July 12, 2013

iomega external drive is not showing up on Mac OS

1. In a terminal run : sudo chflags nohidden /Volumes/*

Since I did not know the name of my iomega drive I used the wildcard * instead of the name for the external drive.

2. Unplug the power to the external drive and connect it back to your Mac.

It should work now.

Monday, July 01, 2013

How to Setup Amazon Cloud Front in Rails 3.2 app


I bought my domain at namecheap.com. It is hosted at Linode.

Step 1 : I used Linode control panel to create a CNAME. It looks like this:

CNAME Records
Hostname Aliases to TTL
cdn amazon-provided-id.cloudfront.net Default
www clickplan.net Default

Step 2 : Go to Amazon Cloud Front and setup a CDN distribution. I followed the instructions from this blog: http://happybearsoftware.com/use-cloudfront-and-the-rails-asset-pipeline-to-speed-up-your-app.html

Note that you should also provide alternate domain name. In my case it was cdn.clickplan.net.

Step 3 : In production.rb add :

  config.action_controller.asset_host = "amazon-provided-id.cloudfront.net"

You can also setup a CNAME like cdn.yourdomain.com to point to amazon-provided-id.cloudfront.net. I am using https for the entire site. Since I did not have wildcard SSL certificate, it did not work so I am using https://amazon-provided-id.cloudfront.net for now. Amazon also has a documentation that shows how to use SSL with your cname. If you have issues, make sure you clear all the history in the browser and hit the URL to see if you can view the css and javascript.

Monday, June 03, 2013

Friday, May 31, 2013

How to control the order of css file inclusion in Rails 3.2 asset pipeline?

In your application.css remove the require_tree .
Then add the css files one by one in the order you would like it to be included in the html. Like this:

*= require_self
*= require 'form'
*= require 'layout-fix'

and so on. Just leave the require_self as it is. For a detailed explanation: RAILS ASSET PIPELINE HANDLING OF CSS & JS 

Wednesday, May 29, 2013

NoMethodError: undefined method `y' for main:Object

If you want to use the y method to inspect an object in yaml format. Whenever you bring up rails console in development, you can inspect any object.  Just add the following line to your development.rb:

YAML::ENGINE.yamler = 'syck'

How to print text in green in Ruby

text = "This is a test"
irb > print "\033[32m#{text}\033[0m"
This will print the text in green.

NoMethodError: undefined method `buckets' for :AWS::Core::Configuration

Resolution: Use the constructor version of S3 : s3 = AWS::S3.new('your credentials')

Tuesday, May 28, 2013

ignoring config/database.yml

If you already have the config/database.yml file in the repo and you want to ignore it. Follow these steps:

1. Add : config/database.yml to .gitignore file.
2. Rename database.yml to database.yml.sample
3. Check in the changes.
4. Now git will ignore the database.yml that you create in your project.

Keeping Security Credentials Out of Source Code Repository

Moonshine is supposed to keep the file in the shared folder and symlink it to the file under current project folder just by adding one line to the config/moonshine.yml

:shared_config
  - config/amazon_s3.yml

For some reason it created the symlink but it did not upload the file. I had to manually do it by :

cap shared_config:upload

on my laptop. On initial setup it actually worked for database.yml. I think it is because of cap deploy:setup command. Remember to add the config file to the .gitignore file so that it does not get checked into the repo.

Sunday, May 26, 2013

Consuming Webservices deployed on Google App Engine from Rails


Google App Engine is very attractive for exposing services that needs to be up and running 24x7 and scale automatically based on demand. Rails apps can consume RESTful services developed using Google Cloud Endpoints. Even though Google Cloud Endpoints is experimental,  platform developers will find very compelling. Any platform that can make a http request can consume the services.

1. Using OAuth 2.0 for Server to Server Applications
   
2. Google APIs Client Library for Ruby
Here is the github repo :  https://github.com/google/google-api-ruby-client

3. Code to Cloud in under 45 minutes

4. Slides from 18 to 34 from Pycon2013

5. Google Cloud End Points sample project
 
6. Python End Points

7. OReilly Webcast : Python for Google App Engine



The absolute uri: http://www.oracle.com/technetwork/java/javaee/jsp/index.html cannot be resolved in either web.xml or the jar files deployed with this application


To get the guestbook.jsp App Engine example working replace the tag library fn as follows:
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

Monday, May 20, 2013

Error: Cannot find module 'npmlog'


1. npm install -g yo grunt-cli bower gives the error:

Fix : sudo curl https://npmjs.org/install.sh | sh

How to upgrade Node.js


1. Check the version :  $node --version
   output will be like : n@0.9.3 /usr/lib/node_modules/n

2. To upgrade, run : $n 0.9.3
where, 0.9.3 is from the output of step 1.

Open a new terminal and type: $node --version
You should see the upgraded version.
   

Friday, May 17, 2013

SQLite3::BusyException: database is locked: ROLLBACK TO SAVEPOINT active_record_1

Caused SQLite3 to lock due to bug in a test. To fix:

1. ps -a | grep ruby
2. kill -s 9 12345

12345 is the process id that is the zombie rspec process.

Tuesday, May 14, 2013

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


Copied from https://github.com/sparklemotion/nokogiri/issues/742
Moved gem 'nokogiri' in the Gemfile to the top (just below gem 'rails') then:
brew uninstall libxml2
gem uninstall nokogiri
gem install nokogiri

Monday, May 13, 2013

AbstractController::ActionNotFound:


       Could not find devise mapping for path "/users/sign_in?user%5Bemail%5D=bparanj%40gmail.com&user%5Bpassword%5D=secret".
       This may happen for two reasons:
     
       1) You forgot to wrap your route inside the scope block. For example:
     
         devise_scope :user do
           get "/some/route" => "some_devise_controller"
         end
     
       2) You are testing a Devise controller bypassing the router.
          If so, you can explicitly tell Devise which mapping to use:
     
          @request.env["devise.mapping"] = Devise.mappings[:user]

Solution:


  before :each do
    request.env['devise.mapping'] = Devise.mappings[:user]
  end

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