I'm all about Ember.js recently

Exploring Ruby Metaprogramming: Call Counter

A few days ago I purchased a screencast by Dave Thomas on Ruby metaprogramming. (I do not receive any affiliation fees :)). The part I bought presents a problem and describes nine different ways of solving it in ascending order of beauty and code clarity.

I was stunned by its beauty so I came up with another -though similar- problem and put together a simple solution for it. I present it for the Rubyists to silently smile in the knowledge of its elegance and power and for non-Ruby programmers to be -hopefully :)- amazed by it.

The task is to count the calls to a certain method of all instances of a class.

call_counter.rb:

module CallCounter
  def count_calls_to(method_name)
    original_method = instance_method(method_name)
    
    call_counter = 0
    define_method(method_name) do |*args|
        call_counter += 1
        bound_original_method = original_method.bind(self)
        bound_original_method.call(*args)
    end

    define_method "calls_to_#{method_name}" do
        call_counter
    end     
  end
end

call_foo.rb:

require "call_counter"

class CallFoo
    
    extend CallCounter

    def foo; end
    count_calls_to :foo

end

After calling “count_calls_to :foo” in the CallFoo class definition, calls to the “foo” method of CallFoo instances will be counted. A “calls_to_foo” method is available to get this count.

I first created an UnboundMethod with “instance_method” and then used the bind method to attach it to an instance of ClassFoo. All this is to prevent aliasing method names, not because it is necessarily evil but because I agree with Dave Thomas about “bind” being a nicer solution. The define_method acts as a closure and saves its context so there is no need to use an instance variable for call_counter.

You can use the counter like this:

irb(main):003:0> cf = CallFoo.new
=> #<CallFoo:0x608100>
irb(main):004:0> cf.calls_to_foo
=> 0
irb(main):005:0> 4.times { cf.foo }
=> 4
irb(main):006:0> cf.calls_to_foo
=> 4

Once again, what I love about Ruby is that in ~ 20 lines we have laid the base of a benchmarking tool (adding the possibility of measuring time spent in the method would not be hard). Also, the original class is not sullied by the call counting code intrinsic details. That functionality is stashed in a module, eager to be reused again.

You may note there is something not quite nice about this. The method calls are counted per class, which makes sense since we usually want to know how many times the method in question was called in all instances, not per instance. However, the calls_to_foo is called on the instance which is confusing. It should be called on the class object, like this:

4.times { cf.foo }
  CallFoo.calls_to_foo
  => 4

I may get back to this later.

A Git Guide That Emboldens

Git is extremely powerful. I knew that much and that I would really like to thoroughly master it because it is so cool. However, it is quite sophisticated (not to mention that some commands, like checkout and revert designate totally different actions than in Subversion where I am coming from) and like with most things one learns by doing.

One key to doing is the ability to play around with a git repository. The possibility to have an account on github.com and to contribute to a myriad of open source projects there removed that obstacle. The other ingredient to be a master chef is a good guide in the subject. One needs some initial self-confidence to know what he is doing lest he screws up his own work. (Note: that is very hard with git but I remember the panic when I did “git checkout <earlier commit>” and I did not find my earlier HEAD with “git log” )

We may be different but I have not read a really insightful guide albeit I have gone through a dozen of them. Some are too vague or concentrate on one specific task (e.g how to create a repo on github and push to it) and some present too many options and go into details that intimidate the novice. (like the official man pages). Ladies and gentlemen, I have found it. It’s the Git User’s Manual and it strikes the perfect balance between verbosity and shallowness. It gives examples which nicely clarify the concepts. It won’t make you an expert right away, of course, but it provides you with the insight and initial courage to embark on the journey.

Installing Rmagick

I needed to install rmagick for a Rails project. I had some amount of trouble along the way but finally succeeded so I am sharing my experience in case you bump into the same problems.

I first installed the binary OS-X distribution of imagemagick (no problems here) and then attempted to install rmagick, the ruby interface to the ImageMagick libraries:

sudo gem install rmagick

However, I received the following unpleasant error:

Can't install RMagick 2.7.2. Can't find MagickCore.h.

I checked that the header file is there (on the path the install script was looking for it), and decided not to go the hard way. After some googling I found there is a rmagick-osx-installer which downloads, compiles and installs ImageMagick and rmagick. Just what I needed.

However, the script failed to accomplish its mission, it hung when installing rmagick. Taking a peak in its log I saw several other errors so I had to look for another way. And that way was compiling the ImageMagick library myself. So I downloaded the source, made the configuration-make-make install cycle and fortunately everything went smoothly. The good news is I could install rmagick without any problem after that:

balint$ sudo gem install rmagick
Building native extensions.  This could take a while...
Successfully installed rmagick-2.7.2
1 gem installed

Refuting Rails Myths

David Heinemeier Hansson, the creator of Rails is doing an outstanding series of blog posts on his blog to derail (pun intended) some common myths that claim Rails does not do this or that and that hinders (or rather, slows down) its widespread acceptance.

I am sure David holds his best for last and will refute the infamous “Rails does not scale” in the final episode of the series.

ConferenciaRails 2008: Enhorabuena!

I have just returned from Madrid where the Spanish Rails Conference, Conferencia Rails was held. I liked it quite a lot, there were several interesting talks most of which made me want to learn all of that and very fast (one thing conferences do to me is to boost that healthy feeling of wanting to always learn and discover new things). So I would like to add my e-voice to the web noise: congratulations and thank you to the organizers and presenters!

Blackbird - Simple Log Messages in Javascript

Using alert() for debugging javascript is a pain. Firebug makes it a lot easier and enables several debug facilities (e.g inserting breakpoints, stepping into methods, adding variable watches) but a painless logging mechanism would still be very useful to supplement Firebug’s features.

Enter Blackbird, a simple javascript logging tool which has a very clean, nice API and a cool console. It’s really worth to check out, you can download the Blackbird files here and my demo here to try out its features. (If you use my demo, you have to save the Blackbird files in a directory named blackbirdjs that is situated in the same directory as the demo page)

Blackbird’s motto says it all: say “hello” to Blackbird and “goodbye” to alert().

Javascript Method Chain

John Resig has an extraordinary advanced javascript tutorial on his blog that he presented on a web conference. It is definitely worth a walk-through since it expands one’s javascript horizon unless one has not written a javascript framework himself.

I played around with several of his slides learning a lot. My favorite was probably the last slide which explains how method overloading works using the fact that methodname.length in javascript gives back the number of expected arguments of that function.

function addMethod(object, name, fn){ 
  // Save a reference to the old method 
  var old = object[ name ];
 
  // Overwrite the method with our new one 
  object[ name ] = function(){ 
    // Check the number of incoming arguments, 
    // compared to our overloaded function 
    if ( fn.length == arguments.length ) 
      // If there was a match, run the function 
      return fn.apply( this, arguments ); 
 
    // Otherwise, fallback to the old method 
    else if ( typeof old === "function" ) 
      return old.apply( this, arguments ); 
  }; 
} 
 
function Ninjas(){ 
  var ninjas = [ "Dean Edwards", "Sam Stephenson", "Alex Russell" ]; 
  addMethod(this, "find", function(){ 
    return ninjas; 
  }); 
  addMethod(this, "find", function(name){ 
    var ret = []; 
    for ( var i = 0; i < ninjas.length; i++ ) 
      if ( ninjas[i].indexOf(name) == 0 ) 
        ret.push( ninjas[i] ); 
    return ret; 
  }); 
  addMethod(this, "find", function(first, last){ 
    var ret = []; 
    for ( var i = 0; i < ninjas.length; i++ ) 
      if ( ninjas[i] == (first + " " + last) ) 
        ret.push( ninjas[i] ); 
    return ret; 
  }); 
} 
 
var ninjas = new Ninjas(); 
assert( ninjas.find().length == 3, "Finds all ninjas" ); 
assert( ninjas.find("Sam").length == 1, "Finds ninjas by first name" ); 
assert( ninjas.find("Dean", "Edwards").length == 1, "Finds ninjas by first and last name" ); 
assert( ninjas.find("Alex", "X", "Russell") == null, "Does nothing" );

It took me some time to figure out how exactly the method calls are routed but it was an interesting process nevertheless. I guess the one tricky part to interpret is the following bit:

if ( fn.length == arguments.length ) 
  // If there was a match, run the function 
  return fn.apply( this, arguments ); 
 
  // Otherwise, fallback to the old method 
  else if ( typeof old === "function" ) 
    return old.apply( this, arguments ); 
  }; 

This makes a method chain and allows for method overloading. With the three addMethod calls in the above example a chained method is built up.

After the call to addMethod with no arguments (the first one), the find method of the Ninjas “class” will return all ninjas if called with no arguments and do nothing if called with any number of arguments. After the call to addMethod with one single name argument the find method will return the ninjas whose first name matches the passed argument if there is only one argument, return all ninjas if it has been called with no arguments and do nothing otherwise.

I could go on but the pattern is probably clear now. At each call of the find method, the lastly added method is matched for the number of arguments (so in the above example, it will match if the caller passed two arguments) and the method called if the match is successful. Otherwise, it will try to match the number of arguments with the method that was added before the last one, and so on.

I am elaborating this in so much detail because

  1. it was such a “Eureka!” moment for me when I got it.
  2. it is an incredibly ingenious way to flex the possibilites of javascript and introduce an OOP concept into an originally non-OOP language.

I think John Resig made javascript lovable again which is why he deserves my total gratitude.

My First DSL in Ruby

I read a few posts about how good fit Ruby is for building DSLs, Domain Specific Languages. Ever the curious I have been waiting for the opportunity to build a very simple one for a particular problem.

Well, I did not have to wait very long (when you have a hammer everything looks like a nail). I needed a quick method which generates nice html graphs for my post about browser javascript engine benchmarking. After spending a few minutes searching for a free tool (I did not want anything fluffy, just something very basic) I hit the nail in the head with my hammer. Only the nail was the generated HTML charts for my post and the hammer, (my desire to build) a DSL in Ruby.

I would like to say it was difficult but in fact it was a piece of cake with Ruby (and armed with the knowledge of previous DSL builders). The solution is composed of the following three parts:

  1. The DSL file which defines the charts
  2. The interpreter which understands the definitions in the DSL file
  3. The “controller” which just passes the data contained in the DSL file to the interpreter

So let’s see each part separately:

browser_js_benchmarks.dsl (the DSL)

chart "Score" do |c|
    c.add "Safari 3.1.2" => 164
    c.add "Firefox 3.0.1" => 156
    c.add "Shiretoko" => 145
    c.add "Google Chrome" => 1589
end

chart.rb (the interpreter)

require "math_aux"

class ChartDSL
    
    Template = %(%%ITEMS%%
%%CAPTION%%
) Background_colors = %w(red blue green yellow grey) attr_reader :values def initialize @charts = Array.new @values = Hash.new end def chart(name) @name = name yield self @charts.push(make_html) end def add(name_and_value) @values ||= Hash.new @values.merge!(name_and_value) end def load(filename) # c = new instance_eval(File.read(filename), filename) write_output end def make_html sorted_pairs = @values.sort_by { |v| - v[1] } vals = sorted_pairs.map { |p| p[1] } norm_values = MathAux::normalize(vals, 100.0) html = Array.new sorted_pairs.each_with_index do |pair, i| name, value = pair html.push(%Q(#{name}
 
#{value})) end filled_chart = ChartDSL::Template.sub("%%CAPTION%%", @name) filled_chart.sub("%%ITEMS%%", html.join) end def write_output File.open("generated_charts.html", "w") do |f| f.write(@charts) end end end

chart_loader.rb (the controller)

require "chart"
class ChartLoader
    def self.load_chart(dsl_filename)
        c = ChartDSL.new
        c.load(dsl_filename)
    end
end

if __FILE__ == $0
    ChartLoader.load_chart(ARGV[0])
end

For the sake of completeness here is math_aux.rb:

module MathAux
    def self.normalize(numbers, to=1.0)
        norm_rat = to / numbers.max
        numbers.map { |n| n * norm_rat }
    end
end

To generate the charts, one only has to run “the interpreter” with a dsl file as the first parameter:

ruby chart_loader.rb browser_js_benchmarks.dsl

The output is called generated_charts.html and contains the following:

Score
Google Chrome
 
1589
Safari 3.1.2
 
164
Firefox 3.0.1
 
156
Shiretoko
 
145

Note that in ~30-40 code lines we have a “language interpreter”, one that understands the chart DSL and spits out some HTML code that represents the charts. Of course there is plenty of room for improvement, like having the same color denote the same actor between charts (Firefox 3.0.1 should always be the blue bar, for example, unlike in my post), using a better solution for the template strings, adding the possibility of pie charts (although “standard” HTML is not very flexible on different chart forms, one would probably have to use a <canvas> ), and so on.

The essential thing is that it works and it does what the particular situation demanded. It took me a couple of interrupted hours plus the time to read through two related posts which is not that much given that I now have a “tool” (once again, I feel a bit conceited to call it that) which I can use for my future posts whenever the need arises. A custom hammer for my custom nail.

(If you care, feel free to download, use and modify the source code located here)

V8 Javascript Engine Benchmarks

A few weeks back when I read about Chrome I became interested in V8, a javascript engine that Google integrated in their browser and that they claimed to be very fast due to the following reasons:

  • Hidden class transitions that enable dynamic optimizations since objects will use the same (hidden) class
  • generating machine code instead of interpreting the source code each time
  • incremental garbage collection which reduces the time needed for the cleanup to milliseconds and eliminates “second long pauses”

All that sounded very promising but as an engineer by profession it left me with a desire to find out how much faster all these features made V8 (and any browser that might use it). Even more so since I love running benchmarks and compare numbers. Well, maybe Google sensed that since they provided all the necessary tools to run these tests on the V8 benchmark page and to run them very easily.

There are 5 different algorithms in the testing suite exercising different qualities of the javascript engine. To be fair I closed all other tabs in browsers during the testing attempting to minimize operations that can have an effect on test performance. Also, the V8 tests were run from the command line so that might skew the results a bit towards V8. Anyyway, here are the results (numbers mean execution time so smaller is better):

Richards
Google Chrome
 
2072
Firefox 3.0.1
 
152
Shiretoko
 
116
Safari 3.1.2
 
91
DeltaBlue
Google Chrome
 
1753
Firefox 3.0.1
 
171
Safari 3.1.2
 
127
Shiretoko
 
123
Crypto
Google Chrome
 
1415
Firefox 3.0.1
 
150
Shiretoko
 
150
Safari 3.1.2
 
135
RayTrace
Google Chrome
 
1021
Safari 3.1.2
 
232
Firefox 3.0.1
 
126
Shiretoko
 
114
EarleyBoyer
Google Chrome
 
1933
Safari 3.1.2
 
328
Shiretoko
 
259
Firefox 3.0.1
 
188
Score
Google Chrome
 
1589
Safari 3.1.2
 
164
Firefox 3.0.1
 
156
Shiretoko
 
145

The superiority of V8 stunned me so much even to push me to ask whether all this is possible. Googe Chrome that uses V8 is on average (see Score) 10 times faster than all the other browsers (that pretty much flock together). I expected to find the speed of Firefox 3.1 (codename Shiretoko) close to that of Chrome but to my surprise it does not even surpass that of the other browsers. That made me a bit disappointed since I am a big Firefox fan.

Can it be that these benchmarks are somehow tailored to show V8’s dominance? (like some political polls are skewed to give the “correct” answer). That this is not such a far-fetched idea is supported by Mozilla’s announcement that TraceMonkey, Firefox’s javascript engine will be 16-28% faster than V8. And they have their own benchmarking solution, SunSpider to prove their point.

So the life of javascript engine developers has got a lot harder. Not only they have to implement a fast engine but also a benchmarking system that shows there is nothing as fast as theirs!

Navigator for the Google Chrome Comicbook

The first beta version (for now only for Windows) of Google’s browser is out, but I don’t think Google needs the marketing power of my post so that’s not what I want to talk about. The browser is introduced by a ingenious comics of 39 pages. However, the navigator is too simple, in my opinion in that you cannot skip a page so if you read until say page 19 and you have to start over (e.g you closed the browser), you have to click on the “Next” link 18 times. There is no unique URL for each page, the whole navigation is done with a javascript snippet changing the image (the cartoon strip) when the user clicks “Prev” or “Next”.

So I took a peep at the source of the page and reverse-engineered the navigation which is simply a javascript call to goPage(‘next’) when the user clicks the Next link. So now I can simply write

javascript:for (var i=0; i < 10; i++) goPage('next');

to the location bar to skip 10 pages ahead and do the same with ‘prev’ to rewind 10 pages.

I know “reverse-engineering” is way too conceited a term for this but this kind of hacking tickles my brain in a very joyful way and feels a bit like outsmarting Google. And that’s not bad at all.

UPDATE: I now realize the comics’s navigation has been redesigned so my above fix became obsolete. At least I cherish the knowledge my hack addressed a real UI problem (and did that faster than Google :) ).