Debugging Rails Applications in Development

I’ve been spending a lot of time answering questions on “Stack Overflow”:http://stackoverflow.com/ lately. From what I read, most of the questions come from unexperienced developers. It’s not easy to understand their questions because they often lack code examples, stack-traces or application logs. Because of that I keep repeating a lot of stuff in the comments or in my answers. I thought that it might be better to write everything down in a blogpost, so everyone has a chance to pick it up all at once.

h2. The basics

When working with Ruby on Rails you will have to learn a lot of stuff to master debugging your own application. There are so many moving parts in a Rails app, it’s not just MVC…

* Views (Partials, Layouts, Templating-Engines)
* Controllers (Actions, Filter)
* Models (Relations, AREL, Callbacks, Database-Systems)
* Mailers
* Routes (REST, HTTP-Verbs, Constraints)
* Environments and Initializers
* Caching (Redis, Memcached)
* Assets (CSS, SASS, JavaScript, CoffeeScript, Pipelining)
* Bundler and dependency management
* Tests (RSpec, Capybara)
* gems, plugins and engines used in the app

WOW, that is a LOT and I probably forgot some stuff…

Because of this overwhelming complexity, it is very important to know the basic tools that come with Rails and that help me in my “everyday computering”:https://github.com/phoet/computering.

h3. Using rake

Rake was intended as a Make for Ruby. It’s basically a build-tool that handles tasks. It has become the swiss-army-knife of Ruby and Rails. So make sure you know when it can be useful for you! The basic commands are rake -T to get a list of _public_ commands and rake -D to get the full description of the tasks. If one of the commands fail, you can pass the --trace option to see what rake is doing under the hood and find possible error causes.

Here is a list of useful commands that I use when running into strange errors during development:

rake routes
rake middleware
rake assets:clobber
rake assets:clean
rake tmp:clear
rake log:clear

h3. Reading stack-traces

It is happening to me all the time. The application spits out an error and I have no clue what is going on. Providing meaningful error messages is one of most neglected parts in writing maintainable software. On average, Ruby is very helpful in that regard, Rails is not! Nevertheless, you should always read the errors and stack-traces because they contain helpful information like the _source file_ and the _line number_ where an error was caused. It even provides information about the context, like the calling object and the call-stack when the error happened.

Let me give you “an example exception”:http://stackoverflow.com/questions/19317128/why-i-am-getting-undefined-local-variable-or-method-role-in-cucumber-test-case/19319592:

undefined local variable or method `role' for # (NameError)
  ./features/step_definitions/event_steps.rb:10:in `create_visitor'
  ./features/step_definitions/event_steps.rb:14:in `create_user'
  ./features/step_definitions/kid_steps.rb:107:in `/^I am exists as a parent$/'
  features/manage_kids.feature:11:in `And I am exists as a parent'

What I can see at a glance:

* it’s about cucumber
* we are in a step definition
* the context object is of class Cucumber::Rails::World
* there should be a role but it is not available
* calling create_visitor caused this error
* the source of create_visitor is in event_steps.rb on line 10

The source code that matches this error is this:

# event_steps.rb
def create_visitor
  @visitor ||= { 
    :email => "[email protected]",
    :password => "test123", 
    :password_confirmation => "test123", 
    :role => Role.find_by_name(role.to_s) # this is line 10
  }
end

It is just an excerpt of the code, so it’s a good idea to add real line-numbers or an anchor so other people know where we are. In this example, this would not even be necessary, because _role_ is only called once. Without knowing anything about the source, I can immediately see that the author wanted to use something that is not there.
So possible solutions to this might be to use _@role_ or maybe [email protected]_ or to have a method called _role_ or pass it in as a parameter to that method. If the test has run successfully before doing any changes, the error was probably introduced by some changes you did and should be easy to find.
_So always make sure your test suite passes before writing new code_.

h4. Side Note

Never throw away exception information unless there is a good reason! Swallowing exceptions causes a lot of pain for people that have to maintain the running application, so please at least log the error message when you rescue from something.

h3. Reading code

One of the key skills for writing code is reading code in the first place. Whether it is code I wrote some time ago, code of my coworkers or library code. It’s super important to understand the code at hand and the code that my application is executing. Compared to other languages, where one has to deal with compiled sources, it’s incredibly easy to have a look at ruby sources. I often run bundle open some_gem to look at the source or when you are not using bundler run gem env and look at GEM PATHS where your gems are installed

gem env

RubyGems Environment:
  - RUBYGEMS VERSION: 2.1.5
  - RUBY VERSION: 2.0.0 (2013-06-27 patchlevel 247) [x86_64-darwin12.4.0]
  [...]
  - GEM PATHS:
     - /Users/paule/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0
  [...]

subl ~/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/rails-4.0.0/

I also often use “dash”:http://kapeli.com/dash to get method documentation.

h2. Debugging the running server

Rails coding is often CMD+R driven. I sit in front of the browser and reload the page to see if something happens… Unluckily it does not work the way I expected, so what to do next?

h3. It’s in the logs stupid!

When I am working on a Ruby or Rails application i like to run stuff in “iTerm2”:http://www.iterm2.com with split views. One session for running spec, rails or the console and one session with the corresponding logs with tail -f log/development.log

Screen Shot 2013-10-16 at 10.22.00

Logs help with a lot of stuff and are a powerful tool to debug your running code. Things that can be extracted from the logs:

* direct error information
** error-messages
** complete stack-traces
** logged warnings or errors (attribute accessible warnings, deprecations)
* context information
** request parameters
** request types (html, json, xhr…)
** response codes
** sql queries
** rendered views and partials
** callback informations

Since Rails introduced the asset pipeline, logs became pretty useless, because they were cluttered with asset calls. Disabling those logs does not need any ugly middleware monkey patches anymore because you can use the “quiet_assets gem”:https://github.com/evrone/quiet_assets for this purpose!

One thing that I do to pimp my logs to be even more useful is to use the “tagged logger”:http://weblog.rubyonrails.org/2012/1/20/rails-3-2-0-faster-dev-mode-routing-explain-queries-tagged-logger-store/ that was introduced in Rails 3.2. It allows you to put “even more context information into the log like the session-id and request-id”:https://github.com/phoet/on_ruby/blob/master/config/application.rb#L36:

# application.rb
config.log_tags = [
  :host,
  :remote_ip,
  lambda { |request| "#{request.uuid}"[0..15] },
  lambda { |request| "#{request.cookie_jar["_on_ruby_session"]}"[0..15] },
]

h3. Quick inspects

There are a couple of “workflows” which I tend to use in my everyday debugging, starting with simply adding p some_object, puts some_object.inspect or logger.debug some_object calls randomly to the code. For view templates i use = debug(some_object).
This helps in about 50% of the error cases because it gives me enough context to find the problem quickly.

Another thing is putting a raise some_object.to_s into the code. This is especially helpful if I want to find out when and how some part of the code is executed. Callbacks are a good example where this is a nice shorthand method for debugging.

h3. Insight tools

A running Rails server can provide a lot of useful information for debugging, especially if you curry it with the right helpers. Rails 4 already comes with some better error reporting and a route helper that can be accessed through navigating to an unknown route (“thx ecki for the clarification”:http://nofail.de/2013/10/debugging-rails-applications-in-development/#comment-14539). I use the /routes path for this purpose:

Screen Shot 2013-10-16 at 13.04.18

This functionality can be improved with a nice UI and a mini Rails console running in your browser if you add “Better Errors”:https://github.com/charliesome/better_errors and the “Binding of Caller”:https://github.com/banister/binding_of_caller gem. These tools allow you to dive right into the error context and find out what might have went wrong. Combining this with raising my own errors gives me a lot of flexibility to quickly get to the point where I assume that something fishy is going on in the code.

Screen Shot 2013-10-16 at 13.02.46

When you are doing a lot of ActionMailer related stuff, you probably want to install the “Letter Opener gem”:https://github.com/ryanb/letter_opener to develop and inspect your E-Mails.

h2. The debugger

Having tools like Better Errors is super nice, but they are only suited for usage in the Browser. This is not always possible and I fall back to real “debuggers”:http://en.wikipedia.org/wiki/Debugger that allow for moving around in the call-stack and inspecting objects at runtime.

The “ruby-debug gem”:http://bashdb.sourceforge.net/ruby-debug.html was the go-to-guy for a long time in Ruby land. It was a PITA to get this up and running in latest Ruby versions. That’s why I use the IRB replacement “pry”:https://github.com/pry/pry with a lot of extensions like “pry-debugger”:https://github.com/nixme/pry-debugger or “pry-nav”:https://github.com/nixme/pry-nav. If you want to hook into a remote Rails process (ie. running rails via foreman) you can hook into it with “pry-remote”:https://github.com/Mon-Ouie/pry-remote. Have a look at the “Pry Railscast”:http://railscasts.com/episodes/280-pry-with-rails for more information.

h2. Debugging through the console

The console is very important for me when writing new or changing existing code. I often create new finders and scopes in the console directly. A very important command in the console is reload!. It reloads all the code in the current session, similar to what happens when you hit CMD+R in the browser:

reload!; something_i_changed_in_the_editor.check_if_it_works

A thing that I find very helpful when stuck in a debugging session is the method.source_location functionality introduced in Ruby 1.9. It allows me to see where a method is defined:

user.method(:url).source_location
=> ["/Users/paule/Documents/rails/on_ruby/app/models/user.rb", 39]

h3. Use the force Luke

I like to use “pry-rails”:https://github.com/rweng/pry-rails as my default Rails Console. It enables me to browse source code, inspect objects and do a lot of other crazy stuff. Just type help in a pry session to see what commands are available. My favorite command is wtf? which shows the last raised exception and stack-trace.

h2. Debugging through testing

I love test driven development! It is an everyday part of my programming routine. The only thing that I hate when doing TDD in Rails is the slow feedback loop. I don’t like using tools like “spork”:https://github.com/sporkrb/spork-rails or “zeus”:https://github.com/burke/zeus as they introduce a lot of complexity and make debugging even harder.

So my approach to get away with minimal turnaround time is to start my new expectations by writing somthing like this:

describe User do
  it "does crazy stuff" do
    pry
  end
end

This rspec expectation will just open a new pry session where I can start coding right away, exploring my test with direct feedback from executing the code I want to test. This eliminates all the iteration- and startup time when running red/green cycles. It is especially useful when I don’t know exactly how something should function in the first place…

h3. Debugging capybara

The last pattern is super useful when writing “acceptance tests in capybara”:https://github.com/jnicklas/capybara! I always forget how to use capybara expectations and matchers, because I write only a few of those tests. This is mainly due to “the test pyramid”:http://blog.codeclimate.com/blog/2013/10/09/rails-testing-pyramid/ and me being a backend developer.

There are also a lot more moving parts in acceptance tests, especially when running JavaScript tests in a headless browser. It’s super useful when you can just check page.body or temper with X-PATH expressions directly in the pry session.

If there is some strange behavior during test execution, I just put a breakpoint somewhere in the test and call save_and_open_page or even better: print out current_url and open the running test instance directly in the browser!

h2. Other helpful tools

The Rails ecosystem comes with a lot of tools for debugging, but it can be enhanced even further:

h3. Rails Panel

If you are using Google Chrome like me, you can use the “Rails Panel plugin”:https://github.com/dejan/rails_panel in combination with the “Meta Request gem”:https://github.com/dejan/rails_panel/tree/master/meta_request to get a Rails Developer Console in your browser. Super sweet!

Screen Shot 2013-10-16 at 11.21.51

h3. cURL

If I want to look into response headers or other request/response specific information, I use curl in addition to the Chrome Developer Tools:

curl -I "http://hamburg.onruby.dev:5000/"

HTTP/1.1 200 OK
[...]

It is even possible to use the “Copy as cURL” option in the Chrome Developer Tools to get all the parameters necessary to redo some request!

h3. Navicat

I use “Navicat”:http://www.navicat.de/ as a multi db frontend. It allows me to inspect what is going on in the database, check query results, indices and create data on the fly. Always have a good client for your data stores available!

h3. GIT

“I love git”:http://git-scm.com/book! It’s not the most self explanatory tool on the planet but it helps me so much when debugging applications. Just one example here is using git bisect. It executes a command for a range of commits, so that it is possible to find out which commit introduced a problem I am trying to debug.

h2. Resources worth reading

Here are some websites that I keep referring to in a lot of my answers on stackoverflow. Go ahead and check all of them, really, I mean it!

* “Rails Guides”:http://guides.rubyonrails.org/ (“Edge Guides”:http://edgeguides.rubyonrails.org/)
* “The Ruby Pickaxe”:http://www.ruby-doc.org/docs/ProgrammingRuby/
* “RailsCasts”:http://railscasts.com/
* “API Dock”:http://apidock.com/rails
* “Ruby-Toolbox”:https://www.ruby-toolbox.com/

OMG, Apple rejected my App!

After releasing my first RubyMotion app (“FC St.Pauli chants”:http://nofail.de/chant/), I’m currently working on “another one”:https://github.com/phoet/freifunk_ios/ for “Freifunk Hamburg”:http://hamburg.freifunk.net/.

I am using “Testflight”:https://testflightapp.com/ with a group of 10+ beta testers, to verify that my app is working properly and has no issues whatsoever.

h2. The Review Process

When I think that an app is close to be feature complete, I create a version that can be pushed to the AppStore. This process involves setting up a distribution certificate and other stuff in iTunes connect. It’s a little time consuming and the review-process usually takes some weeks, especially for new apps.

I was not totally surprised that the first revision got rejected by Apple, eventhough they stated, that the app crashed on startup, which none of my beta testers had experienced. I thought that this might be due to some iOS 7 related changes.

So I just submitted an updated version to the review process. Unfortunately that version also got rejected…

h3. The Crash Report

The latest reject was also due to a crash on startup. In case of a crash, Apple provides a “Crash Report”:https://gist.github.com/phoet/abfe691b2c4fce9d8c0d in the Resolution Center (it’s super easy to find… NOT: iTunes Connect>Manage Your Apps>[The App Icon]>View Details>Links>Resolution Center).

There is a lot of info in such a crash report. It starts with some basic infos about the device and app environment:

Incident Identifier: 7B2A05A2-E9C3-47F8-90DC-3C37BA634D69
CrashReporter Key:   edb549cbc4b5919b7c8a04beb0db00da1ada7c41
Hardware Model:      xxx
Process:             freifunk [6726]
Path:                /var/mobile/Applications/44317BE9-04A0-4B3E-A3D8-24134AE1B06C/freifunk.app/freifunk
Identifier:          de.nofail.freifunk
Version:             0.0.1 (0.0.1)
Code Type:           ARM (Native)
Parent Process:      launchd [1]
 
Date/Time:           2013-09-13 08:06:36.406 -0700
OS Version:          iOS 7.0 (11A465)
Report Version:      104

then comes the root cause:

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Triggered by Thread:  0

followed by the backtrace when the crash occured:

Last Exception Backtrace:
(0x2fe08f4e 0x3a6156aa 0x2f85ac 0x2f86d8 0x2608f4 0x25df9c 0x2c78f8 0x2e887c 0x2e003a 0x2c81c4 0x232d50 0x2e8854 0x2e003a 0x22f9e8 0x22fc60 0x2302f0 0x325eacb2 0x325ea702 0x325e4d0e 0x3257f6a2 0x3257e9a4 0x325e44f8 0x34a38708 0x34a382f2 0x2fdd39e2 0x2fdd397e 0x2fdd2152 0x2fd3cce2 0x2fd3cac6 0x325e3794 0x325dea3c 0x42d9c 0x42860)

infos about the threads that were active during the crash:

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
[...]
9   CoreFoundation                	0x2fd3cd58 CFRunLoopRunSpecific + 636
10  CoreFoundation                	0x2fd3cac6 CFRunLoopRunInMode + 102
11  UIKit                         	0x325e3794 -[UIApplication _run] + 756
12  UIKit                         	0x325dea3c UIApplicationMain + 1132
13  freifunk                      	0x00042d9c 0x32000 + 69020
14  freifunk                      	0x00042860 0x32000 + 67680
 
Thread 1 name:  Dispatch queue: com.apple.libdispatch-manager
Thread 1:
0   libsystem_kernel.dylib        	0x3abc183c kevent64 + 24
1   libdispatch.dylib             	0x3ab02220 _dispatch_mgr_invoke + 228
2   libdispatch.dylib             	0x3ab01fa6 _dispatch_mgr_thread$VARIANT$mp + 34
 
Thread 2:
0   libsystem_kernel.dylib        	0x3abd4c7c __workq_kernreturn + 8
1   libsystem_pthread.dylib       	0x3ac3adc6 _pthread_wqthread + 306
2   libsystem_pthread.dylib       	0x3ac3ac80 start_wqthread + 4
 
Thread 3 name:  WebThread
Thread 3:
[...]
6   WebCore                       	0x37ebebae RunWebThread(void*) + 414
7   libsystem_pthread.dylib       	0x3ac3cc1a _pthread_body + 138
8   libsystem_pthread.dylib       	0x3ac3cb8a _pthread_start + 98
9   libsystem_pthread.dylib       	0x3ac3ac8c thread_start + 4

Thread 4:
0   libsystem_kernel.dylib        	0x3abd4c7c __workq_kernreturn + 8
1   libsystem_pthread.dylib       	0x3ac3adc6 _pthread_wqthread + 306
2   libsystem_pthread.dylib       	0x3ac3ac80 start_wqthread + 4
 
Thread 0 crashed with ARM Thread State (32-bit):
    r0: 0x00000000    r1: 0x00000000      r2: 0x00000000      r3: 0x00002060
    r4: 0x00000006    r5: 0x3ca9318c      r6: 0x00000000      r7: 0x27dce594
    r8: 0x1450efa0    r9: 0x00000001     r10: 0x14569fb0     r11: 0x00000000
    ip: 0x00000148    sp: 0x27dce588      lr: 0x3ac3da33      pc: 0x3abd41fc
  cpsr: 0x00000010 

and the address space:

Binary Images:
0x32000 - 0x334ffb freifunk armv7  <3ae0aadc89773fe8a07f885fdaff2237> /var/mobile/Applications/44317BE9-04A0-4B3E-A3D8-24134AE1B06C/freifunk.app/freifunk
0x2bee8000 - 0x2bf0878a dyld armv7   /usr/lib/dyld
0x2edd9000 - 0x2edd9fff Accelerate armv7  <8e17835efc9234da89e3080c47fad906> /System/Library/Frameworks/Accelerate.framework/Accelerate
[...]

h3. Analyzing the Report

It’s not obvious what to do with such a report so Apple gives a “Technical Note”:https://developer.apple.com/library/ios/technotes/tn2151/_index.html on this topic. You can also find some information in the “Debugging Guide”:http://www.rubymotion.com/developer-center/articles/debugging/#_debugging_symbols of the RubyMotion docs.

The big problem with the crash report are the missing identifiers. There is no hint for what might stand behind any of the memory addresses noted in the backtrace or whatever. That’s were “Symbolication”:http://stackoverflow.com/questions/1460892/symbolicating-iphone-app-crash-reports comes into play.

h3. Symbolicating your RubyMotion Crash Report

Symbolication is the the process of converting the numeric addresses in the stacktrace to matching parts of the codebase. In order to get this working, you will have to keep the *.dSYM files that were generated with your release build. They are in the same folder as your .ipa file, that you are uploading to the AppStore (ie build/iPhoneOS-5.1-Release/freifunk.dSYM/).

_It’s a good idea to backup those files!_ Otherwise you won’t have the possibility to ever know why a crash happened.

Symbolication is pretty easy “once you know what to do”:https://groups.google.com/forum/#!topic/rubymotion/ib3wHcHNFWY. You can use the atos command line utility to “convert numeric addresses to symbols of binary images or processes”. Go to the release folder of your app and run the command with the exception backtrace, use the first address of the binary image as your base address and point to the executable binary:

cd build/iPhoneOS-5.1-Release
atos -o freifunk -l 0x32000 -arch armv7 0x2fe08f4e 0x3a6156aa 0x2f85ac 0x2f86d8 0x2608f4 0x25df9c 0x2c78f8 0x2e887c 0x2e003a 0x2c81c4 0x232d50 0x2e8854 0x2e003a 0x22f9e8 0x22fc60 0x2302f0 0x325eacb2 0x325ea702 0x325e4d0e 0x3257f6a2 0x3257e9a4 0x325e44f8 0x34a38708 0x34a382f2 0x2fdd39e2 0x2fdd397e 0x2fdd2152 0x2fd3cce2 0x2fd3cac6 0x325e3794 0x325dea3c 0x42d9c 0x42860

This produces a somewhat readable output:

0x2fe08f4e
0x3a6156aa
__vm_raise() (in freifunk) + 468
rb_vm_raise (in freifunk) + 280
rb_exc_raise (in freifunk) + 4
rb_name_error (in freifunk) + 92
rb_mod_const_missing (in freifunk) + 116
dispatch_rimp_caller(objc_object* (*)(objc_object*, objc_selector*, ...), unsigned long, objc_selector, int, unsigned long const*) (in freifunk) + 272
rb_vm_dispatch (in freifunk) + 4502
rb_const_get_0 (in freifunk) + 684
rb_scope__init_testflight__ (in freifunk) (app_delegate.rb:45)
dispatch_rimp_caller(objc_object* (*)(objc_object*, objc_selector*, ...), unsigned long, objc_selector, int, unsigned long const*) (in freifunk) + 232
rb_vm_dispatch (in freifunk) + 4502
vm_dispatch (in freifunk) + 504
rb_scope__application:didFinishLaunchingWithOptions:__ (in freifunk) (app_delegate.rb:3)
__unnamed_2 (in freifunk) + 316
0x325eacb2
0x325ea702
0x325e4d0e
0x3257f6a2
0x3257e9a4
0x325e44f8
0x34a38708
0x34a382f2
0x2fdd39e2
0x2fdd397e
0x2fdd2152
0x2fd3cce2
0x2fd3cac6
0x325e3794
0x325dea3c
main (in freifunk) (main.mm:15)
start (in freifunk) + 36

The interesting parts here in this stack are rb_scope__application:didFinishLaunchingWithOptions:__ (in freifunk) (app_delegate.rb:3) and rb_scope__init_testflight__ (in freifunk) (app_delegate.rb:45). They show that the app crashes during initialization in didFinishLaunchingWithOptions when calling the method init_testflight with the error const_missing. This is the matching code part:

  def init_testflight
    TestFlight.takeOff(NSBundle.mainBundle.objectForInfoDictionaryKey('testflight_apitoken'))
  end

So the problem seems to be that TestFlight was missing somehow. This was kind of weird, because I was using TestFlight for distributing my beta builds and all worked fine. Doing some grep in the compiled sources, I saw that the TestFlight SDK was not included in the distribution build. The underlying problem was, that the TestFlight source path was only set in an development block:

  app.development do
    app.testflight.sdk = 'vendor/TestFlightSDK'
    [...]
  end

Moving out of there fixed my crashing App version.

So the “Freifunk App finally made it and you can get the in the AppStore”:http://appstore.com/nofail/freifunk!

So Coded – A Web Conference in Hamburg

On “19th & 20th September 2013”:http://socoded.com/schedule.html there will be the first “So Coded Conference”:http://socoded.com/ in Hamburg, Germany. I just recently joined the awesome team of organizers and as you can imagine, there is a lot of stuff to do…

The conference aims at Ruby, Python, JavaScript, PHP developers and their shared passion for the interwebs. At the conference, there will be space for up to 150 coders at “a sweet location, the LOLA”:http://www.lola-hh.de/ in “Hamburg Bergedorf”:http://socoded.com/travel.html, _to learn, teach, hack and have fun_! “The nice LOLA-Bar”:http://www.lolabarhamburg.de/ is open to relax and chill in between sessions or to hack on your projects.

The team of organizers did a great job already to get in touch with “some awesome folks”:http://socoded.com/speakers.html, but we are still reaching out to international speakers to present an incredible lineup for the attendees. “Engine Yard”:https://engineyard.com/, “GitHub”:https://github.com/, “6wunderkinder”:http://www.6wunderkinder.com/, “Travis CI”:http://travisci.com/ just dropping some names…

*If this sounds cool and interesting for you, “grab one of the few early bird tickets”:https://tito.io/so-coded/so-coded left!*

And if you think that your company should support So Coded, have a look at “the sponsoring section”:http://socoded.com/sponsors.html.

“computering” – a different presentation style

Keynote is nice, but it’s not well suited for technical presentations. Live coding on the other hand is hard and often fails horribly because of some minor typos etc.

Some month ago I visited the “Python Usergroup Montreal”:http://montrealpython.org/ and I saw an awesome live coding session from “Rory Geoghegan”:https://github.com/rgeoghegan. He was typing incredibly fast and 100% correct! Watching him, at first I was baffled, then I was amazed and then I got suspicious…

Rorey used “Keyboard Cat”:https://github.com/natw/keyboard_cat.vim to replay his code!

h2. The “computering” gem

If you are into Programming-Screencasts like me, you should definitively watch the “PeepCode Play by Play episode with Aaron Patterson and Corey Haines”:https://peepcode.com/products/play-by-play-aaroncorey. In that episode they have a pairing session on some Ruby code. At some point they drift off and start _computering_ with _dinosaur-hands_:

(Find all animated GIFs at the “PeepCode Blog”:https://peepcode.com/blog/2013/charismatic-duo)

Based on the Keyboard Cat and inspired by the _dinosaur-hands_ i created “computering”:https://github.com/phoet/computering. With the _computering_ command line application you can pretend to type amazingly fast and 100% accurate even in _dinosaur-hands-mode_!

_computering_ is just a couple of days old, but you can already build interactive command line presentations with it using a simple Ruby-DSL. I used it for our last “Ruby Usergroup Meeting”:http://hamburg.onruby.de/events/ruby-usergroup-hamburg-juli-2013 and held a talk called “OMG Rails4!”:https://gist.github.com/phoet/5966205

Screen Shot 2013-07-11 at 20.20.08

just don’t do it – the art of being lazy

One thing that I find myself doing a lot is skipping a lot of required programming tasks. From what you can find “on the Interwebs”:http://bit.ly/14xsphr only a “lazy programmer”:http://blogoscoped.com/archive/2005-08-24-n14.html “is a”:http://voices.yahoo.com/a-good-programmer-lazy-programmer-692952.html “good programmer”:http://www.codinghorror.com/blog/2005/08/how-to-be-lazy-dumb-and-successful.html!

This does not mean that you should be doing nothing though… it’s all about “getting things done”:http://en.wikipedia.org/wiki/Getting_Things_Done instead of getting stuck in the details!

h2. don’t test your code

I am a huge fan of “BDD”:http://en.wikipedia.org/wiki/Behavior-driven_development and “Test First”:http://www.extremeprogramming.org/rules/testfirst.html. It’s hard writing all those tests when you are lazy. That’s why people tend to write Happy Path tests only.

I think that there are also a lot of areas, where writing tests does not even make sense. IE when you are creating prototypes, learning new frameworks or whole languages and when you are trying to sketch out an object model in code. In those cases, I don’t skip tests altogether, but I defer it to the point where I am confident with what I am going to create.

When you look at large Rails applications they usually have several layers of tests. Unit, Functional, Integration etc. Unfortunately, every layer of tests adds a layer of complexity. I have seen a lot of projects where people write “Capybara Spec”:https://github.com/jnicklas/capybara or “Cucumber Features”:https://github.com/cucumber/cucumber-rails that try to cover the whole application logic! Those test-suites are often brittle and slow, maintenance is a huge PITA. I rather remove those tests and stick with Unit-Tests that might not cover all integration points, but are easy to maintain, understand and also fast.

Use full stack tests only for mission critical features. If you have a good monitoring and deployment process in place, fixing bugs can be cheap. What’s worse, slow and fragile tests, or no tests at all?

h2. don’t refactor your code

I did a lot of refactoring, especially in large legacy systems, some times with no tests as a safety-net. Refactoring is not a value in itself. If a piece of software does it’s job, why would you even think about refactoring it?

“Clean Code”:http://www.clean-code-developer.de/ is something that you want to achieve in every software project. That is because clean code promises to be easier to change and maintain. So it’s not actually about clean, but changeable code. Refactoring code to make it beautiful is waste, always strive to make it more modular and in this regard, easier to change in the future.

I have set up some strickt rules for when I refactor a piece of code:

* I am changing it anyways in order to add a feature or fix a bug.
* I am totally pissed of the way it is implemented!
* I am sitting on a plane and have nothing else to do…

h2. don’t optimize your app

I don’t know how much time I wasted in discussions with other programmers, claiming that this or that part of an application needs some optimization. Most of the time it’s even worse, people implement optimized software right away… This thing, also known as “Premature Optimization”:http://en.wikipedia.org/wiki/Program_optimization#When_to_optimize or how I call it Premature Ejaculation, is most often the source for the NR. 2 reason of why I refactor code (I’m pissed off).

Optimized code tends to be more complex or less readable and in 99% of all implementations, there is a simple, clean, readable and actual faster way to implement it anyways.

Especially code complexity or the complexity that frameworks introduce in order to be super fast comes with a big downside: decreased productivity! It feels like I spent a whole developer year just fixing bugs related to the Rails Asset Pipeline and “I am not the only one”:https://twitter.com/chriseppstein/status/164386237870903296.

h2. don’t think out of the box

It’s a good thing when you are confident with your programming language, you know every shortcut of the IDE that you use, you run a database that you deeply understand and that you are able to tweak, your operating system is up for half a year and you know what buttons to push to keep it running!

There is no value in introducing new technologies to your application stack until you have a real need for it. **Stability and Know-How are often underestimated!** I think it makes absolute sense to squeeze the last drop of performance out of your existing stack, keep it as long as you can!

It’s a different thing for programmers though. Playing with new frameworks, databases, operating systems and coding in different types of IDEs is key for expanding your horizon. Learning a new programming language each year is one of those things, that keeps you up to date and lets you think about coding problems from different perspectives. But do you want to have all those languages, frameworks and databases in your application stack? Is it worth introducing heterogeneous systems to your company’s infrastructure?

h2. don’t automate

There are tons of tasks in your daily workflow that could be automated. Automation is a key factor in terms of productivity. If you want to have fast and sound processes in your business, automation is probably the way to go.

On the opposite, I think that it’s fine to be doing manual tasks! It’s always a tradeoff between the value that the manual task provides, versus the cost that creating an automated tool, it’s maintenance and support costs.

Is it worth setting up a whole CI infrastructure, when all you have is just a single app to test? Well, it depends… As a lazy developer, I would look for “services that do the heavy lifting”:https://travis-ci.org/ for me.

h2. Conclusion

Create something, put some sugar and cream on top, ship it!