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.