Wednesday, February 04, 2015

TDD is Dead - Part 2 Concise Version

Can TDD lead to design damage? 

This entire debate would not have occurred if DHH had read this quote by Matsuo Basho:

Do not seek to follow in the footsteps of the wise. Seek what they sought.
David's objections:
  1. Unnecessary indirection and complexity required to make it easier to test in isolation.
  2. Using mocks to isolate from external dependencies

The design David showed wasn't due to TDD, the real issue is that these indirections are all good tricks under some circumstances and we need to understand whether they are worth the cost or not. 

Kent said that developers' make one design decision at a time. TDD puts an evolutionary pressure on a design, people have different preferences for the grain-size of how much is covered by their tests. David replied that there's a direct correlation between the size of code and how easy it is to change it.

David said the reason people wanted isolation was due to TDD. You can't just swap out an in-memory store for a call to a web service because they have different operational characteristics. These swap-ability pipe-dreams aren't the real goal - the real goal is isolated testing. Kent agreed that you can't treat in-memory and web services the same as the failure cases are different. The boundaries between elements will leak to some degree "the question is how much are we willing to spend to get how much decoupling between elements".

Kent saw the difference between 10 lines of code and 60 as a cohesion issue. David agreed but argued that cohesion and coupling are often opposed. Higher coupling is usually worth the price to get better cohesion. Kent observed that there are other ways to eliminate external dependencies, you can also use intermediate results, this is what happens with compilers.

Something that's hard to test is an indication that you need a design insight, it's often useful to get up and take a walk to find those insights that lead to better designs that are also more testable.

 Kent clarified he wasn't talking about TDD, but about software design in general, it's not about TDD it's about how to get feedback. Thinking about software design is the thing, because it pays off so big when you get a good design insight. Getting these insights isn't about your workflow, it's about things like knowing when to work and when to rest, gathering influences from other places, collaborating with other people.

Executive Summary
DHH is not seeking what Kent Beck is after:
  1. Fast Feedback Loop
  2. Cheap Way to Test Ideas
  3. Gaining Confidence  

Reference

Saturday, January 31, 2015

Deploying Static Sites on Google App Engine

Why Google App Engine?

1. Hosted on Google infrastructure, so it's going to be fast.
2. If it's a low traffic site, then it's almost free.

Steps

1. Python 2.7 must be installed on your machine. If you are on Mac, it's already installed.
2. Download GAE SDK for Python.
3. Create new application for your static site using GoogleAppEngineLauncher.
4. Create a directory called static under your-site-name directory.
5. Copy the following sample app.yaml for a static site:

application: essentialtdd
version: 1
runtime: python27
api_version: 1
threadsafe: yes

handlers:
- url: /(.*\.(appcache|manifest))
  mime_type: text/cache-manifest
  static_files: static/\1
  upload: static/(.*\.(appcache|manifest))
  expiration: "0m"

- url: /(.*\.atom)
  mime_type: application/atom+xml
  static_files: static/\1
  upload: static/(.*\.atom)
  expiration: "1h"

- url: /(.*\.crx)
  mime_type: application/x-chrome-extension
  static_files: static/\1
  upload: static/(.*\.crx)

- url: /(.*\.css)
  mime_type: text/css
  static_files: static/\1
  upload: static/(.*\.css)

- url: /(.*\.eot)
  mime_type: application/vnd.ms-fontobject
  static_files: static/\1
  upload: static/(.*\.eot)

- url: /(.*\.htc)
  mime_type: text/x-component
  static_files: static/\1
  upload: static/(.*\.htc)

- url: /(.*\.html)
  mime_type: text/html
  static_files: static/\1
  upload: static/(.*\.html)
  expiration: "1h"

- url: /(.*\.ico)
  mime_type: image/x-icon
  static_files: static/\1
  upload: static/(.*\.ico)
  expiration: "7d"

- url: /(.*\.js)
  mime_type: text/javascript
  static_files: static/\1
  upload: static/(.*\.js)

- url: /(.*\.json)
  mime_type: application/json
  static_files: static/\1
  upload: static/(.*\.json)
  expiration: "1h"

- url: /(.*\.m4v)
  mime_type: video/m4v
  static_files: static/\1
  upload: static/(.*\.m4v)

- url: /(.*\.mp4)
  mime_type: video/mp4
  static_files: static/\1
  upload: static/(.*\.mp4)

- url: /(.*\.(ogg|oga))
  mime_type: audio/ogg
  static_files: static/\1
  upload: static/(.*\.(ogg|oga))

- url: /(.*\.ogv)
  mime_type: video/ogg
  static_files: static/\1
  upload: static/(.*\.ogv)

- url: /(.*\.otf)
  mime_type: font/opentype
  static_files: static/\1
  upload: static/(.*\.otf)

- url: /(.*\.rss)
  mime_type: application/rss+xml
  static_files: static/\1
  upload: static/(.*\.rss)
  expiration: "1h"

- url: /(.*\.safariextz)
  mime_type: application/octet-stream
  static_files: static/\1
  upload: static/(.*\.safariextz)

- url: /(.*\.(svg|svgz))
  mime_type: images/svg+xml
  static_files: static/\1
  upload: static/(.*\.(svg|svgz))

- url: /(.*\.swf)
  mime_type: application/x-shockwave-flash
  static_files: static/\1
  upload: static/(.*\.swf)

- url: /(.*\.ttf)
  mime_type: font/truetype
  static_files: static/\1
  upload: static/(.*\.ttf)

- url: /(.*\.txt)
  mime_type: text/plain
  static_files: static/\1
  upload: static/(.*\.txt)

- url: /(.*\.unity3d)
  mime_type: application/vnd.unity
  static_files: static/\1
  upload: static/(.*\.unity3d)

- url: /(.*\.webm)
  mime_type: video/webm
  static_files: static/\1
  upload: static/(.*\.webm)

- url: /(.*\.webp)
  mime_type: image/webp
  static_files: static/\1
  upload: static/(.*\.webp)

- url: /(.*\.woff)
  mime_type: application/x-font-woff
  static_files: static/\1
  upload: static/(.*\.woff)

- url: /(.*\.xml)
  mime_type: application/xml
  static_files: static/\1
  upload: static/(.*\.xml)
  expiration: "1h"

- url: /(.*\.xpi)
  mime_type: application/x-xpinstall
  static_files: static/\1
  upload: static/(.*\.xpi)

# image files
- url: /(.*\.(bmp|gif|ico|jpeg|jpg|png))
  static_files: static/\1
  upload: static/(.*\.(bmp|gif|ico|jpeg|jpg|png))

# audio files
- url: /(.*\.(mid|midi|mp3|wav))
  static_files: static/\1
  upload: static/(.*\.(mid|midi|mp3|wav))

# windows files
- url: /(.*\.(doc|exe|ppt|rtf|xls))
  static_files: static/\1
  upload: static/(.*\.(doc|exe|ppt|rtf|xls))

# compressed files
- url: /(.*\.(bz2|gz|rar|tar|tgz|zip))
  static_files: static/\1
  upload: static/(.*\.(bz2|gz|rar|tar|tgz|zip))

# index files
- url: /(.+)/
  static_files: static/\1/index.html
  upload: static/(.+)/index.html
  expiration: "15m"

- url: /(.+)
  static_files: static/\1/index.html
  upload: static/(.+)/index.html
  expiration: "15m"

# site root
- url: /
  static_files: static/index.html
  upload: static/index.html
  expiration: "15m"

6. Click deploy on GoogleAppEngineLauncher.

Since I bought my domain using Google domains, I configured custom domain to point to my GAE instance by using the Google Developer Console and Google Domains account page as follows.






References

1. Free Static Website Hosting on Google App Engine
2. Google App Engine to Host a Static Site
3. Google App Engine Concole
4. Configuration file

Friday, January 30, 2015

Explicit Use Case Representation in Rails Apps

Here is the notes from my Silicon Valley Ruby presentation:

Opening

Object Oriented Programming promised us re-use and ease of maintenance. OO paradigm delivered on re-use but not on ease of maintenance. Hi, I am Uncle Toni, the rest of the presentation is about how we can overcome the limitation of Object-Oriented Paradigm.

Middle

Ease of maintenance? How? It is relative. When compared to procedural languages, yes. But, this is 2015. We need to be able to quantify the ease of maintenance claim. Given a requirement, can we estimate and come up with how many weeks it will take to finish? Your manager comes to you and asks how long a new feature will take, how do you answer that question?

What do you do to find out the level of effort required to finish the feature on time? You read the Wiki, which is out of date and in sync with the current code base. You read the code. You don't know how the code works. So you talk to the developer who wrote the code. There are communication issues. I cannot estimate unless I have an understanding of the system.

How do we gain an understanding of the system? Can tests help? Cucumber features does not provide trace-ability. Because, the steps create and call methods on it. We cannot get a big picture view of the system that helps us to estimate. It introduces accidental complexity. Bob Martin's suggestions result in bloated code and over-engineering. We don't want Repository pattern and all that Java crap that becomes a heavy burden.   

Let's imagine an ideal world where we are not restricted by any programming paradigm. What does the ideal solution look like? We need a trace-ability matrix that shows which use-cases map to which class and methods. Some of the classes are re-used by more than one-use case so we have some reuse of code. These shared classes are called tangling. The wide spectrum of classes that collaborate to achieve a high-level use case is called scattering. The use-cases are cross-cutting because they cut through different layers of the system. 

In a well-designed system we have layered architecture where we separate the view, the controller and the persistence layer. This allows us to allocate work according to the strength of a developer. As long as we obey the contract between the layers, teams can work in parallel.

How much time do you think you spend on maintenance as a developer? Microsoft did a survey and found out that 90% of the developer time is spent on maintenance. If you reduce that by half, you can save 50% of your maintenance cost.  

Ideally I want to glance at the code and instantly know which part of the code has the use case that my manager is talking about. Read my blog post on why using interactor gem is a bad idea.

I don't use Rails filters for business logic. It is very difficult to reason about the code. I thought only others write bad code. I consult for start-ups, I see code written by inexperienced developers, find missing abstractions. Make the view dumb, thin controller and fat models. Then I realized the projects that I developed from scratch, after a few months when I saw the code base, I had 'WTF' moments. What was I thinking? When does this thing get called? Is it even used anywhere? Can I delete it? How do I use this feature?

Why Not Use Tests for Traceability

People get very clever in tests. Ideally, I want to see 'Once upon a time, lots of things happen, then they lived happily ever after'. The tests does not tell me a story. Here is the link to my solution that aims to be a trace-ability matrix. Maybe one of you can create a gem that will analyze the code and create a nice matrix. This matrix can be kept in sync with the code because it is generated by analyzing the code. It be part of the build system, where a post-checkin hook can get it gets published to the wiki automatically. You can use this as a starting point to do impact analysis. What is the impact of this new requirement? How many classes and methods will have to change? Based on that you will get an idea of the complexity of the new requirement. 

Question from the audience after browsing my code above. Why not put all the uses cases for an actor into the same file? 

Because the only thing I liked about the Interactor gem is that when you open the interactor folder you get a list of all use cases, it shows what the system can do. I don't like the fact that the class names are verbs. Ideally, you want the class names to be noun and the method names to be a verb. I have seen interactor gem more often being abused in the projects that I have been involved. I also think naming the classes with the verb as breaking the basic OO design principles. If you are hitting the limits of OO paradigm, then you need to think about other ways of solving the problem. 

When a failure happens, you have to fail loudly. That means raising an application level exception. The reason is that it is extremely difficult to hunt down bugs that are hidden behind some code that is failing silently. I have spent weeks to find these kind of bugs. If you see the home page of interactor gem, you will see they are checking for a flag to check for success/failure. 

I also don't like the proliferation of so many classes with just one method. Why do we need a class for each step in a use case? It does not make much sense to me.

Possible Solution

Luckily Ruby allows the file name for a class to be anything. So we can have the file name named after the use case name. 

I read the Ivor Jacobson's book Use Case Oriented System written in the 1990's. He talks about describing the use cases that is agnostic of the technology. When a developer works with the use cases, the use cases needs to be converted to objects with responsibilities. Even if you have no semantic gap between your code base and the use cases, you still have a mismatch between the user's perspective and the developer's perspective. You might have concepts in the code that does not have any counter part in the use case or the domain. 

BDD does not mean using Domain Driven Design. DDD is about using aggregates, entities, architectural patterns and so on. It's not just using the terms used in the domain.

One of the paper I read uses Django framework and uses complicated solution where use cases are store in a repository with use case annotation to achieve trace ability. I don't want to over-engineer and complicate things. Non-invasive tools would be better, where I can run a gem like Rails best practices and get a nicely formatted trace ability matrix.

Can DCI architecture address these problems? What if Ruby 3.0 came up with a new language construct? My solution has an entry point into the system, it does not do any work by itself. It delegates all the work to other objects. It orchestrates the entire use case. 

Note for myself: Take a look at concerns and see if you can get rid of the require statements in application.rb.

TDD is Dead Episode 1 Concise Version

David's three major issues with TDD and Unit Testing:
  1. Confusion over the definition of TDD and unit testing, 
  2. Test-induced damage through using mocks to drive architecture
  3. How the red/green/refactor cycle of TDD never worked for him. 
Kent said that programmers deserve to feel confident that their code works, TDD is not the only way to reach that.

David agrees that you're not done till you have tests. But doesn't like TDD as a way to get there. He thinks people have different brains and thus like different techniques, he doesn't like that TDD gets conflated with the confidence you get from writing the tests first.

Kent agrees that there are cases where TDD is not suitable. In the TDDable code he found he was in an enjoyable flow, but found the other part more tricky. But in the non-TDD part he still used regression tests and short feedback loops. He has no problem mixing both styles. TDD reminds him of how he learned mathematics at school - always needing examples.

David has been in situations where TDD flowed well, but most of his work isn't like that - his question is what are you willing to sacrifice to get that flow? Many people make bad trade-offs, especially with heavy mocking.

Kent said he rarely uses them, he's concerned that those that do mock often find refactoring difficult, while he finds testing makes refactoring easier.

David said his reaction was to seeing people describe TDD in a mock-heavy style as a moral thing to do and the result was a lot of code that was poorly designed due to its desire to enable isolated unit tests.

Next episode will explore how TDD may lead to design damage. This is the concise version of the transcript of the video : Is TDD Dead?

Wednesday, January 28, 2015

How to download an entire site to your machine


1. brew install wget
2. wget --recursive --no-clobber --page-requisites --html-extension --convert-links --domains somedomain.com http://somedomain.com/index.html

--domains flag indicates don't follow any external links from somedomain.com site.
--recursive flag tells wget to download all the files on that domain
--page-requisites - get all assets (images, CSS etc)
--html-extension : save files with the .html extension
--convert-links : convert links so that they work off-line
--no-clobber : don't overwrite any existing files


Wednesday, January 21, 2015

Top 10 Reasons Why Test Driven Development in Ruby Course is Awesome

Test Driven Development in Ruby Course is a comprehensive online course that covers the basics of Test Driven Development in Ruby for beginners. This course aims to help beginners to overcome difficulty in learning TDD. Each lessons in the course has hands on exercises to reinforce the material. You will learn TDD by applying the concepts in the lessons. At the end of the class, students will have worked through some common interview problems and gained skills that can be used to answer questions in an interview.
TDD in Ruby
  1. This course is designed by a developer for developers
  2. It makes complicated concepts easy to understand
  3. It is hands on step-by-step guide to learning TDD
  4. It gives a solid foundation for a beginner to TDD
  5. You will be doing Test Driven Development in Ruby in less than 4 hours
  6. Access to the entire transcript that is not released to the public yet.
  7. Access to the transcript in audio form that is not released to the public yet.
  8. Lifetime access to 42 lectures and 8 quizzes
  9. 3.5 hours of high quality content
  10. Use the downloadable checklists to guide you when coding
This course is the result of teaching one-day TDD boot-camps and TDD tutorials for Silicon Valley Ruby Meetups. I have spent more than 500 hours and thousands of dollars to create this course. Click on the image below to enroll for this course now.


TDD in Ruby

TDD in Ruby

Friday, December 05, 2014

Upgrading from Rails 4.1.4 to Rails 4.1.8

Problem when upgrading from Rails 4.1.4 to Rails 4.1.8

rails -v
Bundler is using a binstub that was created for a different gem.
This is deprecated, in future versions you may need to `bundle binstub rails` to work around a system/bundle conflict.
Rails 4.1.8


Fix:
$rm -rf bin/*
$bundle exec rake rails:update:bin
zepho-mac-pro:lafon zepho$ rails -v
Rails 4.1.8


Monday, November 24, 2014

Deploying a Rails App on Google App Engine

Deploying a Rails Webapp on GAE should be a piece of cake right? Due to lack of good documentation, it is not that easy. I had to dig around to find the versions of the software installed for Ruby Stack One-Click Deploy.

Here is some useful information to access installed software components.
Apache web server:  

Configuration directory: /etc/apache2
Default website directory: /var/www
Command to start Apache web server: sudo service apache2 start
Command to stop Apache web server: sudo service apache2 stop

Passenger:

Help command: passenger --help
Install directory: /usr/local/rvm/gems/ruby-2.1.1/gems/passenger-4.0.48

MySQL:

Command to access MySQL: mysql -u root -p
Command to start MySQL service: sudo service mysql start
Command to stop MySQL service: sudo service mysql stop

RVM, Ruby and Rails:

RVM Help command: rvm
Rails help command: rails -h
RVM install directory: /usr/local/rvm
Ruby install directory: /usr/local/rvm/src/ruby-2.1.1
Rails install directory: /usr/local/rvm/gems/ruby-2.1.1/gems/rails-4.1.4

Git:
Help command: git --help

Saturday, November 22, 2014

bin/rails:6: warning: already initialized constant APP_PATH

I was getting this error in Rails 4.2 beta when I started the rails server. Solution: run : rake rails:update:bin from rails project directory.

git Illegal instruction: 4 mac 10.7.5

Download the git for Mac 10.7.5  and restart your terminal.

Friday, November 14, 2014

Stripe API Capybara Test Failures

I was getting Stripe::InvalidRequestError: You must supply either a card or a customer id error. To fix this, make sure js is true in your integration test like this:

feature 'Guest Checkout' do
  scenario 'Complete purchase of one product', js: true do
    visit products_show_path
    click_link 'Buy Now'
   
    fill_in "Card Number", with: '4242424242424242'  
    page.select '10', from: "card_month"
    page.select '2029', from: 'card_year'
    click_button 'Buy Now'
   
    expect(page).to have_content('Receipt')
  end
end

Thursday, November 13, 2014

Base Ball Player Statistics

Overview:  For this scenario, we have been asked to write an application that will be used to provide information about baseball player statistics.  Approach this problem as if it is an application going to production.  We don't expect it to be perfect (no production code is), but we also don't want you to hack together a throw-away script.  This should be representative of something that you would be comfortable releasing to a production environment.  Also, spend whatever amount of time you think is reasonable.  If you don't get all the requirements completed, that's ok.  Just do the best you can with the time that you have available.  You may use whatever gems, frameworks and tools that you think are appropriate, just provide any special setup instructions when you submit your solution.

Assumptions:  All requests currently are based on data in the hitting file.  Future requests of the system will require data from a pitching file as well.  Consider this in the design.

Requirements: When the application is run, use the provided data and calculate the following results and write them to STDOUT.

1) Most improved batting average( hits / at-bats) from 2009 to 2010.  Only include players with at least 200 at-bats.
2) Slugging percentage for all players on the Oakland A's (teamID = OAK) in 2007. 
3) Who was the AL and NL triple crown winner for 2011 and 2012.  If no one won the crown, output "(No winner)"

Formulas:
Batting average = hits / at-bats
Slugging percentage = ((Hits – doubles – triples – home runs) + (2 * doubles) + (3 * triples) + (4 * home runs)) / at-bats
Triple crown winner – The player that had the highest batting average AND the most home runs AND the most RBI in their league. It's unusual for someone to win this, but there was a winner in 2012. “Officially” the batting title (highest league batting average) is based on a minimum of 502 plate appearances. The provided dataset does not include plate appearances. It also does not include walks so plate appearances cannot be calculated. Instead, use a constraint of a minimum of 400 at-bats to determine those eligible for the league batting title.


Data:  All the necessary data is available in the two csv files attached:

Batting-07-12.csv – Contains all the batting statistics from 2007-2012.  
Column header key:
AB – at-bats
H – hits
2B – doubles
3B – triples
HR – home runs
RBI – runs batted in

Master-small.csv – Contains the demographic data for all baseball players in history through 2012.


Please note: We are looking for you to demonstrate you knowledge related to common software practices to include reusability, portability, and encapsulation – to name a few. Work submitted should be in project form and implemented as you were implementing any production solution.


Tuesday, November 11, 2014

How to share files between Virtual Box Ubuntu with Mac OS host computer

1. Create a folder in your Mac home directory, let's say ubuntu-sf.
2. Install guest additions. Click Devices -> Guest Additions and run the installer.
3. Reboot VM
4. Select the Ubuntu image on VM, go to Settings -> Shared Folders
5. Browse to the folder on your Mac you want to share (ubuntu-sf). Name the shared folder (ubuntu-sf)
6. On Ubuntu terminal, run : sudo adduser your-username vboxsf
7. On Ubuntu terminal run: sudo mount -t vboxsf ubuntu-sf /home/bparanj/ubuntu-sf
   Here ubuntu-sf is the name of the shared folder we created in step 5. /home/bparanj/ubuntu-sf is the folder in the
   Ubuntu.


References

How to share files between Virtual Box Ubuntu and host computer
How to automatically mount a folder and change ownership from root in virtualbox


some of the partitions you created are too small ubuntu 12.04 LTS Precise Pangolin

I was getting this error during installation of Ubuntu on Virtual Box. Solution: Increase the hard disk size from default 8GB to something higher. It worked for 45GB.

Tuesday, November 04, 2014

How to get web_console working in Rails 4.2.beta4 project

1. Add the gem to Gemfile.

group :development do
  gem 'web-console', '2.0.0.beta3'
end

2. bundle

3. You can go to the web console by going to the URL : http://localhost:3000/console

You will also see the web console on the bottom of the browser. You can experiment with the Rails environment loaded.

4. You can add "<%= console %>" to any views and play with the web console.

If you restart the server. You need to reload the page to get a new active console session.

For more details : Web Console Ruby Gem

Problem installing nokogiri on Mac OS 10.7.5

Problem: Make sure that `gem install nokogiri -v '1.6.3.1'` succeeds before bundling.

Solution: bundle config build.nokogiri --use-system-libraries
Then run : bundle

libv8 and therubyracer installation problems on Mac OS 10.7.5

The error message is : Make sure that `gem install libv8 -v '3.16.14.7'` succeeds before bundling.
Solution: gem install libv8 -v '3.16.14.7' -- --with-system-v8

Make sure that `gem install therubyracer -v '0.12.1'` succeeds before bundling.
Solution : Change the Gemfile to specify the libv8 version:

gem 'libv8', '3.11.8.13' 
and run bundle

Sunday, October 19, 2014

Copy to Clipboard in Linux

1. Install xclip : sudo apt-get install xclip
2. Copy test.txt to clipboard : cat test.txt | xclip
3. Acess the text from the clipboard: xclip -o

Reference:

1. Copy Output of a Command to Clipboard

Wednesday, September 24, 2014

Changing PDF Meta Data in Ruby

According to the home page of pdf-toolkit gem :

pdf-toolkit allows you to access pdf metadata in read-write in a very simple way, through the pdftk commandline tool.

1. Install pdftk version 2.02

$ pdftk -version

pdftk 2.02 a Handy Tool for Manipulating PDF Documents
Copyright (c) 2003-13 Steward and Lee, LLC - Please Visit: www.pdftk.com
This is free software; see the source code for copying conditions. There is
NO warranty, not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

2. gem install pdf-toolkit

3. Read or Write pdf meta data.

require 'pdf/toolkit'

pdf = PDF::Toolkit.open('tmux_p3_0.pdf')
#puts pdf.public_methods(false).sort

puts pdf.author
pdf.author='Daffy Duck'
if pdf.save
  'PDF meta-data saved successfully'
else
  'Failed to save pdf meta-data'
end
# save! to raise exception on failure

puts "after change"
puts "Author"
puts pdf.author
puts 'Title'
puts pdf.title
puts 'Subject'
puts pdf.subject
puts 'Page count'
puts pdf.page_count
puts 'Creator (Publisher)'
puts pdf.creator
puts 'Created At'
puts pdf.created_at
puts 'keywords'
puts pdf.keywords
puts 'producer'
puts pdf.producer
puts 'version'
puts pdf.version
puts 'Updated at'
puts pdf.updated_at

4. Verify the meta-data in Preview -> Tools -> Show Inspector. You will see the author, title, subject, producer, creator, creation date, updated date, number of pages etc.

5. Read the tests in the pdf-toolkit source code to see the available methods.

Tuesday, September 23, 2014

Fast Typing, IDE shortcuts, Fast Coding

It does not matter how fast you type in the keyboard, know every short-cut in the IDE, never use the mouse or how fast you can code. Remember : It's garbage in, garbage out.

The quality of software depends on:

1. Quality of your thinking.
2. Learning from your mistakes. Did you learn from your own mistakes?
3. Are you making new mistakes or oblivious and making the same old mistakes over and over again?
4. Are you learning from the mistakes of others to minimize making mistakes in the first place?
5. Are you learning to master the best practices?
6. Are you reading books by : Martin Fowler, Alaister Coburn, Eric Evans, Robert Martin etc? Are you applying it to your projects?



Friday, September 19, 2014

wrong number of parameters 2 for in stylesheet_link_tag rails

This error occurs with an ambiguous error message. It does not show the line number of the source where the cause of the problem resides. This happened due to sass-rails dependency on sass gem. Since the sass gem was not declared in the Gemfile, the sass-rails upgraded sass gem to 3.4.4 which broke the application layout. By locking the sass gem to a lower version in the Gemfile:

gem sass, "~ 3.2.1"

The sass-rails picked up this version that works.

Monday, September 01, 2014

The Scientific Method of Troubleshooting

Notes from the presentation by Blithe Rocher.

Set of Techniques for Acquiring Knowledge.
Methodical
Systematic

1. Define the Problem
Expected behavior
Actual behavior
Criteria for success

2. Do Your Research
Know your environment
Read the literature
Discussions
Make it fail

3. Establish a Hypothesis
4. Design the Experiment
Divide and conquer
Limit the variables
Try something weird
Hierarchy of Blame

4. Gather Data
Current status
Read the error message

5. Analyze Your Results
 Problem Solved?
Learn anything?
Understand the Why
Future Experiments
Embrace the Success

6. Keep a Good Lab Notebook
You won't remember
Logs aren't enough
Commit messages
Update the docs
Contribute
Blog it
Share the knowledge



Friday, August 22, 2014

How to play with ActiveModel validators in the rails console

1. bundle open activemodel
2. Open the validator.rb file.
3. You can see the comments that shows you how to mixin the validators. Once you mixin, you can add any validator and define a dummy method for the attribute to play with it in the irb:

class Person
  include ActiveModel::Validations
  SSN_REGEX = /your ssn regex goes here/
  validates_format_of :ssn, with: SSN_REGEX
 
 
  def ssn   
    111-11-1111
  end
end

4. Change the ssn method to invalid ssn to test your regex.
 

Thursday, August 21, 2014

How to install Exception Notification gem in Rails 4.1

1. Add the gem to Gemfile:

gem 'exception_notification'



bundle install

2. In config/environments/production.rb:

Whatever::Application.config.middleware.use ExceptionNotification::Rack,
  :email => {
    :email_prefix => "[Whatever] ",
    :sender_address => %{"notifier" },
    :exception_recipients => %w{exceptions@example.com}
  }

3. Configure ActionMailer, in config/environments/production.rb:

I am using Sendgrid SMTP API so:

config.action_mailer.delivery_method = :smtp

If you have sendmail installed on the production server:

config.action_mailer.delivery_method = :sendmail

4. In production.rb:
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true

How to install pdftk on Mac OS

You can download the installer from https://www.pdflabs.com/tools/pdftk-server/

After installation, open a new terminal and check installation:

$ pdftk --version

pdftk 2.02 a Handy Tool for Manipulating PDF Documents
Copyright (c) 2003-13 Steward and Lee, LLC - Please Visit: www.pdftk.com
This is free software; see the source code for copying conditions. There is
NO warranty, not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$

Wednesday, August 20, 2014

How to create .ruby-version and .ruby-gemset in RVM

rvm --create --ruby-version use ruby-2.1.2@r42
Reference: Create .ruby-version and .ruby-gemset

How to install latest version of Rails

gem install rails --version=4.2.0.beta1

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  |