Last Updated:

Code Safari: almost sinatra, almost readable

Sinatra is a minimal web framework for creating Ruby web applications with minimal effort. Almost Sinatra is the same, but only in eight lines of code. Surely some trick in the movement? Let's take a look at these lines.

# almost-sinatra/almost_sinatra.rb %w.rack tilt backports INT TERM..map{|l|trap(l){$r.stop}rescue require l} $n=Sinatra=Module.new{extend Rack;a,D,S,$p,q,Application=Builder.new,Object.method(:define_method),/@@ *([^n]+)n(((?!@@)[^n]*n)*)/m,4567,a %w[get post put delete].map{|m|D.(m){|u,&b|a.map(u){run->(e){[200,{"Content-Type"=>"text/html"},[a.instance_eval(&b)]]}}}} Tilt.mappings.map{|k,v|D.(k){|n,*o|$t||=(h={};File.read(caller[0][/^[^:]+/]).scan(S){|a,b|h[a]=b};h);v.new(*o){n.to_s==n ?n:$t[n.to_s]}.render(a,o[0].try(:[],:locals)||{})}} %w[set enable disable configure helpers use register].map{|m|D.(m){|*_,&b|b.try :[]}};END{Handler.get("webrick").run(a,Port:$p){|s|$r=s}} %w[params session].map{|m|D.(m){q.send m}};a.use Session::Cookie;a.use Lock D.(:before){|&b|a.use Rack::Config,&b};before{|e|q=Request.new e;q.params.dup.map{|k,v|params[k.to_sym]=v}}} puts "== almost #$n/No Version has taken the stage on #$p for development with backup from Webrick"

That's it. Of course, it's tight! There are a few gems here, so let's start collecting them piece by piece. Reading confusing code is a great way to delve into the deep end and really understand the syntax of the language, and by the end of this article, you'll be ready to move around and leave dirty plates on the couch.

First line

I took the first line and reformatted it a few at a time to make it easier to read. This is always my first step when working with confusing code. Often, renaming variables to something meaningful can also be helpful, although I didn't do that in this article.

%w.rack tilt backports INT TERM..map{|l| trap(l) { $r.stop } rescue require l }

What is this original syntax? It looks like a list with a given call #map, but it doesn't look like a list I've seen. This type of code is difficult to find information because a punctuation search is rarely useful. Given that it looks like an array, I took a punt and searched for "ruby array syntax", which opened the "arrays" section in the ruby programming wikibook:

%w is essentially an abbreviation for the String method, where substrings are separated only by spaces.

The above example uses ' as a delimiter', and by using irb we can confirm that we can use any punctuation after %w . Choosing what to use is purely a matter of style.

%w'rack tilt' # => ["rack", "tilt"] %w.rack tilt. # => ["rack", "tilt"] %w(rack tilt) # => ["rack", "tilt"] %w!rack tilt! # => ["rack", "tilt"]

Now let's turn our attention to the contents of the list – it seems to contain both the necessary files and signals for salvation. Because racktilt, and #trap are invalid signal names, calling #trap will throw an exception. Usually in ruby, exceptions are explicitly excluded:

begin trap("bogus signal name") {} rescue ArgumentError => e puts "Invalid signal name" end

Ruby also allows for a finite form, just as you can use if statements.

puts "Small enough" if line_count <= 10 trap("bogus") {} rescue puts ":("

This will save all exceptions, although this is not the cowboy style of behavior that you want to freely distribute through your code base. Not to mention using exceptions to control flow, but when lines are expensive, everything becomes fair play.

Second line

Given the requirements of other preambles, let's dive into the structure itself.

$n = Sinatra = Module.new { extend Rack; a,D,S,$p,q,Application = Builder.new, Object.method(:define_method), /@@ *([^n]+)n(((?!@@)[^n]*n)*)/m, 4567, a

There are some interesting techniques here. The first is the dynamic definition of module. In ruby, everything is an object, even modules and classes, so when you typically use the module keyword to define a module, you can do so on the fly by calling Module.new. The only difference is that the form of the keyword will have an explicit name and a specific constant, whereas the latter will be anonymous.

module Test end Test.name # => 'Test' Module.new.name # => nil

Variable names prefixed with $ are not common, so they may not be familiar to you. A search for "ruby variable types" found an article with a handy table that summarizes the various prefixes, in which case we find that the variable starting with $ is a global variable. That's why you don't see them so often...

Two variable assignment forms are used here. The one used in the first line is based on the fact that everything in ruby implicitly returns a value. You can see this in irb – a value is displayed after each statement executed, even if it is often nil.

# puts returns the value 'nil' irb> puts "hello" hello => nil

The assignment returns an assigned value, which means you can link them together. In the snippet above, this means that the $n and Sinatra will be assigned the same Module.

irb> $n = Sinatara = Module.new {} irb> $n == Sinatra => true

Another assignment trick used is called multiple or parallel assignment, which allows you to assign different values to different variables on the same line. What's interesting about this usage is that one of the variables on the left side of a is reused on the right side to assign the Application constant. I was very confused by this for a while, but after playing irb confirmed that it was actually a bug in the code!

a,Application=1,a # => [1, nil] a=1;Application=a

Line Three

This line configures the methods for the various HTTP verbs, and to understand them, we first need to familiarize ourselves with the Rack::Builder API, since an instance of this class is assigned to the variable D It's a bit tangential, so I'm going to leave that for a future article, and instead focus on two interesting syntactic features that this snippet uses, both related to lambdas and introduced in ruby 1.9.

%w[get post put delete].map{|m| D.(m){|u,&amp;b| a.map(u){ run->(e){ [200,{"Content-Type"=>"text/html"},[a.instance_eval(&amp;b)]] } } } }

The first is a new way to call lambas and procs .(), #call is a #call alias. Thus, the total number of ways to call lambda in ruby is three.

add_two = lambda {|x| x + 2 } add_two.call(1) # => 3 add_two.(1) # => 3 add_two[1] # => 3

There are subtle differences: . () Always delegates #call whereas [] can be overridden separately, but for the most part they are equivalent.

Another interesting syntax is run->(e){} . This is affectionately known as the "stabby" syntax, and it's a new way of defining lambda expressions that was introduced to allow you to specify default argument values. For the ruby parser, it would not be possible to use the old run(lambda {|e| }) syntax (more details if you are interested).

add_two = lambda {|x| x + 2} add_two = ->(x) { x + 2 } # The same! double_or_add = ->(a,b=a|2) { a + b } # Just try that with the old syntax...

The old syntax will last forever, but the new way gives you a less detailed, more flexible option.

And the rest

I told you, it was tight! A whole article, and we only have three lines. On the other hand, it's halfway through the framework! In a short period of time, we looked at a lot of interesting syntax:

  • %w array syntax
  • Ultimate rescue syntax
  • Anonymous modules that use Module.new
  • Chain assignment ( a = b = 1 )
  • Multiple assignment ( a,b = 1,2 )
  • . Syntax for calling code blocks
  • - >() Stable syntax for writing lambdas

The rest of the lines are basically more the same, but there are a couple of curved balls. For practice, I recommend that you continue to work through them. Other projects to sharpen your knife:

  • Camping, pocket web microframe with pocket 4k. It's an old school that's been around for years. It includes an unlimited version and, as such, is a relatively mild introduction to obscure code.
  • It's old, but entries in the 2005 Ruby Code International Code Competition are reflected in this blog post.

Let us know how you go in the comments. Tune in for next week for more exciting adventures in the jungle of code.