Wednesday, August 20, 2014

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.

Monday, December 16, 2013

Ruby on Rails - Enterprise Application Development Notes

Business Processes

In building small business apps, a developer is endeavoring to model or support a business process.

To realize the maximum potential for small business application development, the developer needs to take on the role of analyzing the business process.

To keep up a supply of new work, the developer needs to identify potential new projects and development opportunities.

The key skill to being able to identify opportunities for new apps is an understanding of how businesses work. Study business processes.

Take courses on business management and management accounts. Checkout SBIC library and other libraries. It helps you to identify the best opportunities to improve business processes.

To be successful, build successful business apps. A business application is successful when an application generates a profit. Demonstrate that you can increase their profits. How do small applications generate profit? There are three ways to generate more profit within a business.

1. Increase sales by either increasing the number of sales or increasing the revenue from each sale (or less easily, both)
2. Reduce what it costs you to sell.
3. Spend as little as you can on the parts of the business that generate the least profit and minimize any resources given over to loss making activities.

Business apps can address all of these profit opportunities. Most businesses try to increase profits by increasing sales. It is usually far easier to increase profits by reducing costs and minimizing the time spent on loss making activities. It is in these areas that most opportunities for small business apps arise.

Here is some areas where opportunities for small applications arise:

1. Automate Simple Repetitive Jobs

A simple way to reduce costs is to reduce the time it takes to carry out repetitive tasks. Ex: CFO was spending 4 hours running reports. I created an application which generated the report in 5 minutes. That single simple application has saved 100s of hours of work, thereby freeing up the CFO to do more revenue generating work.

2. Rapid and Detailed Reporting

Actively go out and identify the opportunities that can be found within any business. Develop the skills to identify the opportunities for new apps. To do that successfully and repeatedly, you must learn to identify business processes that can be simplified, made more effective and efficient via a small app.

Friday, December 13, 2013

Cucumber Features


http://wiki.github.com/dchelimsky/rspec/rails

Feature: CSR account management
 In order to manage dispute calls
 As a CSR
 I want to create an account to login to the system

 Scenario: Successful account creation
     Given a login with "csr@somedomain.com" and password "secret"
     And login is the same as email address
     When I provide my login and desired password
     Then I should receive an account activation email at "csr@somedomain.com"

 Scenario: Successful account activation
   Given a valid activation link "http://www.somedomain.com/activation-string-for-csr"
   When I follow the activation link
   Then my account should be activated
   And I should be able to login using the login credentials provided during registration
 
 Scenario: Successful login
   Given a valid user name "csr@somedomain.com" and password "secret"
   When I provide my login credentials
   Then I should be logged in to my account with CSR role
   And I should be able to add additional users with CSR role

 Scenario: Forgot password
   Given a valid user name "csr@somedomain.com"
   And I follow forgot password link
   When I provide my email that I used during account registration
   Then I should receive a link to reset my password
   And I should be redirected to password recovery instructions page

 Scenario: Reset Password
   Given a valid reset password link "csr@somedomain.com" for my account in the password reset email
   When I follow the reset password link
   Then I should be able to provide a new password and confirm password
   And I should be able to login with my new password
   And the system sends password reset confirmation link for security purpose

 Scenario: Change the login id for logging into the system  
     Given a valid login id "csr@somedomain.com"
     When I provide my new desired login id "csr@newdomain.com"
     Then I should be able to login using my new login id "csr@newdomain.com"

 Scenario: Add new CSR account
   Given a CSR is logged-in
   When I provide new account details with valid login "newbie@something.com", password "verysecret" and confirm password "verysecret"
   Then the system should send account activation email to the new csr's email address (login id)
 
 Scenario: Successful logout
   Given a valid user name "csr@somedomain.com" and password "secret"
   When I logout
   Then the system should log me out of the system
   And I should not be able to use the features available only to logged in users
 
 Scenario: Features only available to logged in users
   Given a user is logged in
   When I go to my dashboard
   Then I should be able to add new account, update my login id, search, forgot password and logout

 Scenario: Features not available to users who are not logged in
   Given a user is not logged in
   When they access the CSR application
   Then I should not be able to add new account, update login id, search and logout
   And I should be able to login and also use forgot password feature

 Scenario: Failed account creation
   Given a login with characters that is not in the whitelist
   When I provide my login (email address) and password
   Then I should not receive an account activation email
   And I should get an error message stating the password policy (8 to 40 characters in length with list of allowed characters)
   And the system prevents SQL inject attacks
 
 Scenario: Automatic login
   Given a valid login and the user enables remember me feature
   When I login
   Then I should be logged in automatically on subsequent visits to the site
 
 Scenario Outline: Failed Login
   Given the login id is "" and password is ""
   When I enter "" and ""
   Then the error message should be ""
 
 Scenarios: wrong login credentials
   | login         | password              | error                                         |
   | wrong email     | correct password | Email not found                            |
   | correct email | wrong password   | Wrong password                             |
   | wrong email     | wrong password   | Login and Password does not match  |
   

     

Saturday, December 07, 2013

Including lib directory in the path in Rails 4

1. Add the line:

config.autoload_paths += %W(#{config.root}/lib)

to application.rb

2. Add your class to lib folder.

Rails 4 will now load the classes in the lib folder.

Sunday, December 01, 2013

Syntax Highlighting for Rails

1. Add rouge and redcarpet gems to Gemfile.

gem 'rouge'

gem 'redcarpet'

2. Install rouge gem.

$ bundle

3. Create initializer in config/initializers/rouge.rb
require 'rouge/plugins/redcarpet'

class CustomHtml < Redcarpet::Render::HTML
  include Rouge::Plugins::Redcarpet # yep, that's it.
end

4.  Use the HTML class as a renderer in markdown method in app/helper/application_helper.rb:

def markdown(text)
  render_options = {
    filter_html:     true,
    hard_wrap:       true, 
    link_attributes: { rel: 'nofollow' }
  }
  renderer = CustomHtml.new(render_options)

  extensions = {
    autolink:           true,
    fenced_code_blocks: true,
    lax_spacing:        true,
    no_intra_emphasis:  true,
    strikethrough:      true,
    superscript:        true
  }
  Redcarpet::Markdown.new(renderer, extensions).render(text).html_safe
end

5.  For styling the output using Rouge built-in styles, create app/assets/stylesheets/rouge.css.erb with the following code:

<%= Rouge::Themes::ThankfulEyes.render(:scope => '.highlight') %>
or
<%= Rouge::Themes::Colorful.render(:scope => '.highlight') %>
or
<%= Rouge::Themes::Base16.render(:scope => '.highlight') %>

6. In your view app/views/articles/show.html.erb where you have markdown and code mixed, use the markdown helper:
 
  <%= markdown @article.content %>

References
2. You can even use it with RedCarpet

Taking Passion to the Bank

Passion

Develop Web Applications that can become successful SaaS business.

Skill

Learn Full Stack Web Development using Rails.
Has a proven teaching system based on successful teaching methods.

Problem

Developers want to become Full Stack Rails Developer but are not able to learn quickly from existing resources.

Opportunity

Creates effective teaching material by making complicated concepts simple. Developers are able to master the material quickly.

Good businesses provide solutions to problems, in this case : 'How can I easily learn Web Application Development?'

Saturday, November 02, 2013

Focusing on a specific geographical location

To focus my Google Adwords campaign for promoting lead generator ebook, I found all the unique IPs for the downleads by doing (rails 3.2 webapp):

ips = Download.select('DISTINCT ips')

list = ips.collect(&:ip)

Paste the ip list as a single column on the  Convert IP to Country website. Very interesting fact:

50% of the downloads is from USA. So it is better to follow the Google Ad support person's advice of targeting to one or two geographical locations.

Monday, October 28, 2013

Source code formatter for Blogspot

Very useful source code formatter for blogspot

Rails Best Practices

1. gem install rails_best_practices
2. gem install ripper
3. From the root of the project run: 
rails_best_practices -f html .
to generate the report.

Invalid command 'SSLEngine', perhaps misspelled or defined by a module not included in the server configuration

This error is caused if mod_ssl is not installed. On Cent OS : sudo yum install mod_ssl

Imperative Vs Declarative Programming

Imperative Programming

Imperative programming is the oldest programming paradigm. It is based on the Von Neumann-Eckley model of a computer. Programs written in imperative programming languages consist of a program state and instructions that change the program state through assignment statements. Program instructions are imperative in the sense of imperative verbs that express a command.

Examples of imperative languages are assembly, Fortran, Algol, Cobol, Java, C/C++. These languages specify a sequence of operations for the computer to execute.

Procedural abstraction and structured programming are its design techniques.

Imperative Program = Algorithms + Data Structures
-- Nicholas Wirth

Imperative Programming + Procedures = Procedural Programming

Procedural abstraction allows the programmer to be concerned mainly with the interface between the procedure and what it computes, ignoring the details of how the computation is accomplished. Abstraction allows us to think about 'what' is being done, not 'how' it is implemented. Imperative language constructs : assignment, conditionals, looping and data structures.

Flowchart can be used to model imperative programs. For example flowchart for computing Fibonacci numbers.

Declarative Programming

Functional languages and logic languages are declarative. Declarative languages such as SQL, Haskell, Prolog describe the solution space. They provide the knowledge required to get there. They don't describe the steps needed to get there.


Reference :  Presentation by Computer Science Assistant Professor Mary Ellen Weisskopf 

Thursday, October 24, 2013

Solving Problems in Software Development

As software developers we are in the business of solving problems. A problem can be described using multiple representations such as text, diagrams and equations. If you understand the relationship between different representations of a given problem, you will be able to translate one representation to the other. If you are dominant in one representation and when you are given a problem to solve in your weaker representation you can translate into your dominant representation and solve the problem.

1. Understand the Problem

   - What do you need to find?
   - What are the unknowns?
   - What information do you obtain from the problem?
   - What information, if any, is missing or not needed?

2. Devise a Plan

   - Look for a pattern
   - Make a table
   - Draw a diagram
   - Write an equation
   - Work backwards
   - Identify a subgoal
   - Examine related problems and determine if the same technique can be applied
   - Examine a special case of the problem to gain insight into the solution of the original problem.

3. Carry Out the Plan

   - Implement the strategies from the plan and perform the computations.
   - Check each step of the plan as you proceed.

4. Look Back

   - Determine whether there is another method of finding the solution
   - Determine if there are more general problems for which the techniques will work.

References:

1. Billstein, Libeskind and Lott have adopted these problem solving steps in their book "A Problem Solving Approach to Mathematics for Elementary School Teachers (The Benjamin/Cummings Publishing Co.).
2. Technically Speaking: Making Complex Matters Simple by Steven Rudich

Polya's Problem Solving Technique

Polya's First Principle: Understand the problem

- Do you understand all the words used in stating the problem?
 - What are you asked to find or show?
- Can you restate the problem in your own words?
- Can you think of a picture or diagram that might help you understand the
problem?
- Is there enough information to enable you to find a solution?

Polya's Second Principle: Devise a plan

Polya mentions that there are many reasonable ways to solve problems. The skill at choosing an appropriate strategy is best learned by solving many problems. You will find choosing a strategy increasingly easy. Here is a partial list of strategies:

  - Draw a picture
  - Look for a pattern
  - Consider special cases  
  - Solve a simpler problem
 - Make an orderly list
  - Use a formula
  - Solve an equation
  - Guess and check
 - Eliminate possibilities
 - Use symmetry
  - Use a model
  - Work backwards
 - Use direct reasoning
 - Be ingenious

Polya's Third Principle: Carry out the plan

This step is usually easier than devising the plan. In general, all you need is care and patience, given that you have the necessary skills. Persist with the plan that you have chosen. If it continues not to work discard it and choose another. Don't be misled, this is how mathematics is done, even by professionals.

Polya's Fourth Principle: Look back

Polya mentions that much can be gained by taking the time to reflect and look back at what you have done, what worked, and what didn't. Doing this will enable you to predict what strategy to use to solve future problems.

Here is a summary of strategies for attacking problems in mathematics class. This is taken from the book, How To Solve It, by George Polya, 2nd ed., Princeton University Press, 1957, ISBN
0-691-08097-6.

1. UNDERSTAND THE PROBLEM

- First. You have to understand the problem.
- What is the unknown? What are the data? What is the condition?
- Is it possible to satisfy the condition? Is the condition sufficient to determine the unknown? Or is it insufficient? Or redundant? Or contradictory?
- Draw a figure. Introduce suitable notation.
- Separate the various parts of the condition. Can you write them down?

2. DEVISING A PLAN

- Second. Find the connection between the data and the unknown. You may be obliged to consider auxiliary problems if an immediate connection cannot be found. You should obtain eventually a plan of the solution.
- Have you seen it before? Or have you seen the same problem in a slightly different form?
- Do you know a related problem? Do you know a theorem that could be useful?
- Look at the unknown! Try to think of a familiar problem having the same or a similar unknown.
- Here is a problem related to yours and solved before. Could you use it? Could you use its result? Could you use its method? Should you introduce some auxiliary element in order to make its use possible?
- Could you restate the problem? Could you restate it still differently? Go back to definitions.
- If you cannot solve the proposed problem, try to solve first some related problem. Could you imagine a more accessible related problem? A more general problem? A more special problem? An analogous problem? Could you solve a part of the problem? Keep only a part of the condition, drop the other part; how far is the unknown then determined, how can it vary?
Could you derive something useful from the data? Could you think of
other data appropriate to determine the unknown? Could you change the
unknown or data, or both if necessary, so that the new unknown and the
new data are nearer to each other?
- Did you use all the data? Did you use the whole condition? Have you
taken into account all essential notions involved in the problem?

3. CARRYING OUT THE PLAN

- Third. Carry out your plan.
- Carrying out your plan of the solution, check each step. Can you see clearly
that the step is correct? Can you prove that it is correct?

4. LOOKING BACK

- Fourth. Examine the solution obtained.
- Can you check the result? Can you check the argument?
- Can you derive the solution differently? Can you see it at a glance?
- Can you use the result, or the method, for some other problem?


Reference : http://math.berkeley.edu/~gmelvin/polya.pdf

Saturday, October 19, 2013

What vs How in Test Driven Development

Example #1 for What vs How

Music sheet is not music. It is description of music. This is the 'What' or Logical Design.

Music is played using musical instruments. This is the 'How' or the Physical Design. There are many physical designs for a given logical design.

Example #2 for What vs How

John Lennon wrote the song Come Together. This is the 'What'. The examples of 'How' in this case are the performances of :

- Beatles
- Aerosmith
- Michael Jackson

to the same song Come Together.

Separate Logical Design from Physical Design 

How do you separate What from How in our code? Chris Stevenson's TestDox style expresses the subject in the code as part of a sentence.

- A Sheep eats grass
- A Sheep bleats when frightened
- A Sheep produces delicious milk
- A Sheep moves away from sheep dogs

This can be automatically converted to specifications in code :

describe Sheep do
  it 'eats grass'
  it 'bleats when frightened'
  it 'produces delicious milk'
  it 'moves away from sheep dogs'
end

When you think about the system from outside-in fashion you focus on intent. You focus on what you are doing rather than the implementation which is the 'how'.

References

1. Test Driven Development: Ten Years Later by Michael Feathers and Steve Freeman on

Fun Stuff

Search YouTube and watch the videos for Come Together performed by The Beatles, Michael Jackson, Aerosmith and Elton John

Test Driven Development Background


What is Test Driven Development?

You write a test first before you write the code. You use the tests to drive the design.

It uses one of the XP concepts : Test-First programming to achieve another XP concepts : Emergent Design.

In Emergent Design you start delivering functionality that has business value and let the design emerge. You will deliver functionality A with unit tests and then build functionality B. Then refactor to reduce duplication due to A and B and let the design emerge.

Origins of Test Driven Development

Extreme Programming Explained - Embrace Change by Kent Beck
Refactoring by Martin Fowler

Why TDD ?

- It results in simple design and minimal code.
- Higher quality code due to less defects
- Lower cost to maintain
- Brings fun back to programming

When is TDD not applicable?

- Multi-threading
- Asynchronous Code
- Prototyping
- Exploratory work such as Architectural spike
- Checking the structure of user interfaces such as HTML
- Testing usability of user interfaces

What makes TDD difficult

- Doing TDD without pair programming. TDD and pair programming are complementary.
- Existing code base with no tests

Wednesday, October 09, 2013

Flog Scoring


Score of    Means
0-10        Awesome
11-20       Good enough
21-40       Might need refactoring
41-60       Possible to justify
61-100      Danger
100-200     Whoop, whoop, whoop
200 +       Someone please think of the children

Thursday, September 26, 2013

`raise_if_continuation_resulted_in_a_channel_error!': PRECONDITION_FAILED - parameters for queue 'hello' in vhost '/' not equivalent (Bunny::PreconditionFailed)

This error happens when you have a queue that is not durable and you are doing something to assume that it is durable. Change the name of the queue to a new name and make it durable to fix this error.

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