Senior Developer – My Ass!

We were drinking beers recently, when we decided that we needed to do something against this whole _Senior Developer_ bullshit. Every Programmer that has done more than three keystrokes considers himself a _Senior_ these days…

That was when “@rubiii”:http://twitter.com/rubiii and “me”:http://twitter.com/phoet came up with calling ourselves *Señor Developer* and putting a mustache on our “XING profiles”:https://www.xing.com/profile/peter_schroeder2. Some days later “@defsprite”:http://twitter.com/defsprite toped off our idea by creating “a logo and a website”:http://xn--seordeveloper-jkb.com for our crazy idea.

Since then we did a batch of handprinted Señor Developer T-Shirts that we sent out all over the world (i.e. New Zealand, Uruguay). Because handprinting and delivering all the stuff is way too time consuming we are now using “a spreadshirt shop”:http://senordevelopershop.spreadshirt.net/ for this task.

If you like the idea, feel free to follow “@senordeveloper”:http://twitter.com/senordeveloper on twitter!

Karotz + Ruby = Love

I made myself a little present this christmas by putting a “Karotz”:http://www.karotz.com/ under my christmas tree. This little digital bunny robot is the 3rd generation of a gadget that was once known as “Nabaztag”:http://en.wikipedia.org/wiki/Nabaztag.

Karotz can connect to the internet and you can deploy applications on it. It’s a tiny multitalent, speaks, blinks, turns his ears, takes photos and plays musik. The really cool stuff about all this, is that you can also access it via a “REST-api”:http://dev.karotz.com/api/.

I was a little disturbed by the bad documentation of the api, but since Karotz has had a pretty shaken history, I was willing to see over it. Nevertheless “I had a really hard time figuring out how to use the API”:https://groups.google.com/forum/?hl=en#!topic/karotzdev/FPTzH_d8FAU, especially the “interactiveMode sessions”:http://dev.karotz.com/api/interactiveid.html, which are crucial for interacting with Karotz. That’s why I wanted to give you a short HOW-TO wrapup on it.

h2. Basic Setup

First of all you need to have a Karotz up and running, like it’s described in the handbook. Register yourself at karotz.com and click on the “lab”:http://www.karotz.com/lab button at the bottom of the page. Once you registered yourself for all the developer stuff, you need to register a new application for yourself in order to get access to the credentials needed to talk to Karotz.

In order to get your own application, you need to create a “descriptor.xml”:http://dev.karotz.com/dev/register_app.html#descriptor-xml and package it as a zip-file and then load it up to the appstore and then deploy it to your bunny. Here is an example, which exposes the install-id of your application, which you need to accesss your Karotz:


  0.0.1
  
    tts
    ears
    led
    multimedia
  
  external
  
    
  

Have a look at this “Christops Blog”:http://www.christophs-blog.de/2011/09/karotz-command-line-tool/ if you don’t get it working for yourself.

h2. Using the Gem

There are already some code-examples on the “developer-pages”:http://dev.karotz.com/api/signed.html#Php-sample on how to get an _interactive_id_ for your Karotz and some code has been released for Ruby as ruby-karotz “here”:https://github.com/MadsBuus/ruby-karotz and “here”:https://github.com/XVI-kondoh/Ruby-Karotz none of them exposing a nice API or describing the process of how to get all the peaces of the puzzle together. That’s why I am currently writing this…

So here is an example of how to interact with the “karotz gem”:https://rubygems.org/gems/karotz:

Karotz::Configuration.configure do |config|
  config.install_id = ENV['KAROTZ_INSTALL_ID']
  config.api_key    = ENV['KAROTZ_API_KEY']
  config.secret     = ENV['KAROTZ_SECRET']
end

Karotz::Client.session do |karotz|
  karotz.ears
  karotz.led
  karotz.say
  karotz.play
end

This will rotate Karotz ears, blink the LED, say ‘test’ and let it play the A-TEAM theme!

FTW!

Ruby Quirks

Once in a while I come accross some Ruby code where I don’t know why it is doing stuff the way it does…

h2. Ternary Operator

I am using the Ternary Operator quite a lot, because it keeps the code concise and often times more readable then long if-else statements. One thing that I discovered just recently is the following:

val = something ? 'this' : 'that'

If you look closely, you will see that there is not a comparison == but an assignment = operator present. The interesting fact though is where Ruby puts parenthesis in this code:

val = (something ? 'this' : 'that')

Makes a lot of sense, but is not obvious, especially if you are debugging some library code.

Another cool thing that you can do with the operator is nesting:

val == 0 ? 'zero' : val == 1 ? 'one' : 'other'
# is interpreted as
(val == 0 ? 'zero' : (val == 1 ? 'one' : 'other'))

But most of the times you are better of with Switch Cases.

h2. Switch Case

There are some pretty cool features in the Ruby Switch Case. You can switch by class if you like:

case "some string"
when Integer
  puts "i am an int"
when String
  puts "i am a string"
else
  puts "dunno"
end

This works, because Ruby uses the === method to compare in a when block. So the when code above evaluates to:

String === "some string"

The cool thing is that you can implement the === method yourself and add some Ruby magic to the Switch Case.

But be aware of some stuff that might bite you while using Switch Cases! You should know that Ruby allows multiple arguments in a when block:

case val
when 5, 7
  puts "good numbers"
else puts "bad numbers"
end

It’s also important to know that you need to add a newline before writing your block code. It’s also possible to write oneliners by using a semicolon or the then keyword, otherwise the following code will be interpreted as belonging to the when condition:

case val
when 5, 7; puts "good numbers"
when 0 then puts "empty"
when 1, puts "syntax error"
else puts "bad numbers"
end

Older versions of Ruby also supported a syntax with a : at the end instead of a ;, wich looks kind of strange:

case val
when :number: puts "numbers"
else puts "not a numbers"
end

h2. Missing something

Since the Ruby parser allows a lot of flexibility, it’s possible to implement stuff which does not make sense at all. For example this statement which misses the if at the beginning of the condition:

def test_failing
  else puts "invalid"
  end
end

Evaluating this method will fail (or even kill the ruby process):

warning: else without rescue is useless
syntax error, unexpected keyword_end, expecting $end

One thing that happens to me quite often, is that there are implicit things going on if you forget to add commas in your code, while I am not sure how and why they work:

puts "what" "the" "fuck" # => "whatthefuck"
puts String Integer # => Integer

h2. Everything is a Method

Well not everything in Ruby is implemented as a method, but there a lot of things that you can at least use like methods. Did you know for example, that you can call the accessibility modifiers in Ruby like methods? This is pretty handy if you want to mark only some methods:

def my_method; end
private :my_method

It’s also quite important to know that method objects provide a lot of interesting information. Especially if you are doing some serious debugging with a lot of inheritance and Ruby magic involved:

"".method(:class).owner # => Kernel
class A
  def b;end
end
# works only in 1.9
A.new.method(:b).source_location # => ["...test.rb", 3]

When talking about methods, it’s worth knowing the keywords that are used in Ruby and in which context they can be used. A good example for this is the * character, which can be used quite differently:

# as a simple method
1 * 2
# for varargs in method signatures
def method_name(*args)
# for unsplatting arrays
some_method_that_has_three_args(*[1, 2, 3])

You should also be aware that some operators behave different from others:

def some_array
  @some_array ||= []
end

def doit
  some_array << [3,4] # ok
  some_array += [6,7] # raises undefined method `+' for nil:NilClass
end

h2. Predefined Variables

In analogy to Pearl, Ruby provides a bunch of "Predefined Variables":http://www.cs.auckland.ac.nz/references/ruby/ProgrammingRuby/language.html#predefinedvariables that are worth knowing. A lot of them contain information about the current environment, code or execution context.

There are f.e. some extra variables for matching groups in Rubys regular expressions:

"hey_you" =~ /(.*)_(.*)/
$1 # => hey
$2 # => you
$0 # => .../test.rb

Unfortunately $0 has nothing to do with match groups, but is the name of the current executed program...

h2. Naming Best Practices

When working with Ruby you get used to some best practices when it comes to names. This is important, because several thing are evaluated differently depending on up- and downcase:

CONSTANTS_ARE_UPPER_SNAKE_CASE
ClassesAreCamelCase
Modules::Should::Map::To::Folder::Structure

So it is quite surprising that Ruby comes with an Array() method which transforms everything it gets into an array unless it's already an array:

Array("string") # => ["string"]
Array(["string"]) # => ["string"]

It's also worth having a deep look into the Ruby documentation about Arrays and the Enumerable Module, because they provide a bunch of really cool helpers that can save you an everage developers lifetime if you know them by heart.

For "some more cool Ruby tricks have a look at this Rubyinside post":http://www.rubyinside.com/21-ruby-tricks-902.html.

If you feel like sharing some more Ruby wisdom feel free to post a comment or contribute some sugar!

Improved ASIN documentation

Beeing sick sucks, but on the other hand there is a lot of spare time…

So, while sitting on my couch, I created a new resource for documentation of my pet project the “asin gem”:https://github.com/phoet/asin/, which you can “find on heroku”:https://github.com/phoet/asin_web:

ASIN-WEB

If you have any additions or questions feel free to “fork the project”:https://github.com/phoet/asin_web or open up an “issue on github”:https://github.com/phoet/asin_web/issues.

Heroku Cedar Background Jobs for free!

I’m using Heroku mostly for playing around with latest technology and hosting free apps. Since Heroku “changed their pricing model”:http://devcenter.heroku.com/articles/reading-invoice due to the introduction of “the new process model”:http://blog.nofail.de/2011/06/migrating-an-existing-app-to-heroku-celadon-cedar-stack/ some of my apps changed from free to paid, especially those that had some background jobs or nightly crons (I really did not get, why this happend).

h2. Full Stack Background Processes

If you want to run a “resque worker”:http://blog.redistogo.com/2010/07/26/resque-with-redis-to-go/ and a “clockwork process”:http://adam.heroku.com/past/2010/6/30/replace_cron_with_clockwork/ within your web-app, this becomes a costly thing, even if those are just running some minor jobs in the night, because you need to pay for 2 additional dynos.
You could achieve this through defining multiple processes in your Procfile:

# Procfile
web: bundle exec rails server thin -p $PORT
worker: QUEUE=* bundle exec rake environment resque:work
clock: bundle exec clockwork app/clock.rb
heroku scale worker=1 clock=1

h2. Sharing Addon Connections

As Heroku officially announced in their “latest newsletter”:http://newsletterer.heroku.com/2011/07, it’s possible to share connections between multiple apps. In my case, this would be a connection to a redis key-value store, that is provided by “Redistogo”:http://redistogo.com/. It’s as simple as copying the environment configuration for the addon over to the second app:

heroku config | grep DATABASE_URL  --app sushi
=> DATABASE_URL   => postgres://lswlm...

heroku config:add DATABASE_URL=postgres://lswlm... --app sushi-analytics
=> Adding config vars: DATABASE_URL => postgres://lswlm...m/ldfoiusfsf
=> Restarting app... done, v74.

h2. Going Freemium

So the solution for getting back to a free worker setup is combining 3 Heroku apps and a shared Redis connection through Redistogo:

heroku apps:create freemium-web --stack cedar --remote heroku
git push heroku master

heroku apps:create freemium-worker --stack cedar --remote worker
git push worker master

heroku apps:create freemium-clock --stack cedar --remote clock
git push clock master

heroku scale web=1 --app=freemium-web
heroku scale web=0 worker=1 --app=freemium-worker
heroku scale web=0 clock=1 --app=freemium-clock

heroku addons:add redistogo:nano --app=freemium-web

heroku config:add `heroku config -s --app=freemium-web|grep redis` --app=freemium-worker
heroku config:add `heroku config -s --app=freemium-web|grep redis` --app=freemium-clock

I created an “example project running a Rails 3 application with a mounted Resque web, a Resque worker and a clock process with Clockwork”:https://github.com/phoet/freemium.

h2. Even simpler

If you are just looking for a simple solution of running a background process have a look at “crony, a bootstrap project”:https://github.com/thomasjachmann/crony using “rufus-scheduler”:http://rufus.rubyforge.org/rufus-scheduler/.