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.

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

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

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