Though I thought I would only post about technical issues here, I now make an exception. After all, (soft) rules are for breaking occasionally, aren’t they?

So in case you don’t know, there is a nice service out there to record your bike trips that I have recently discovered. It is a Google Maps application where you first search your point of departure then your point of arrival and Gmap Pedometer does the rest for you. Occasionally you have to lend it a helping hand, though, in case the automatic route generation does not work well. It usually does not if you take bicycle roads that does not run paralelly with the highway since the automatic route generation selects the “car route” by default (it seemed to me). You can set up your itinerary in no time and promptly see the distance you did and how much energy you burned during the process (and ultimately also the elevation of your trip).

I also grab the opportunity to tell you how bike tours are the perfect way of tourism for me. You can easily do 40-50kms per day in a moderate pace. In my opinion that’s a perfect middle ground between being too slow and passing by magnificent landscapes and towns in a car. What’s more, there is the thrill of riding your bike, feeling the air against your cheeks, the ability to stop anywhere and the ambiance of adventure that comes with the nomad lifestyle.

One thing I miss is a convenient method to store your trips. According to the site itself, Gmap Pedometer is “A hack that uses Google’s mapping application to help record distances traveled and calories burned during a running or walking workout.” so one should not expect a full-fletched, shiny application but a basic user registration/login method would be handy so I could quickly access my trips. To be able to review your trips, you must store the unique url that is generated for each one in a safe place.

To give you some example routes and also to store a pointer to some trips I would like to be able to access in the future I list the daily routes of two fairly recent bike routes:

The Netherlands (summer 2007)

Amsterdam - Den Haag
Amsterdam - Enkhuizen
Urk - Elburg
Elburg - Appeldoorn (Beekbergen)
Beekbergen - Arnhem (Oosterbeek)

Austria, going along the Danube (summer 2006)

Passau - Obernzell
Obernzell - Feldkirchen
Feldkirchen - Au an der Donau
Au an der Donau - Willersbach
Willersbach - Aggsbach
Aggsbach - Krems

So what are you waiting for? Hope on your bike! :)

ps. Walking trips can also be recorded on the site and there is automatic route generation for walkers, too.

So last time I left you with the promise that I’d return with a solution so that the number of times a certain method was called is a class method which makes more sense than if it was an instance method. So here is the “improved version”:

call_counter.rb:

 
module CallCounter
 
    def count_calls_to(method_name)
      original_method = instance_method(method_name)
 
      unless class_variable_defined?(:@@call_counter):
        class_variable_set(:@@call_counter, {})
      end
 
      call_counter = class_variable_get(:@@call_counter)
 
      define_method(method_name) do |*args|
        call_counter[method_name] ||= 0
        call_counter[method_name] += 1
        bound_original_method = original_method.bind(self)
        bound_original_method.call(*args)
      end
 
      metaclass = class << self; self; end
      metaclass.instance_eval do
 
        define_method(:calls_to) do |m|
          call_counter[m].nil? ? 0 : call_counter[m]
        end
 
        define_method(:reset_counters) do
          call_counter.each_key do |k|
            call_counter[k] = 0
          end
        end
    end
 
  end
 
end

What has changed is the introduction of a class variable that counts the calls on all watched methods and that the number of calls on each method is queried by calls_to(<method name>) instead of calls_to_<method_name>. A bit less magic.

call_foo.rb:

 
require "call_counter"
 
class CallFoo
 
  extend CallCounter
 
  def foo; "foo"; end
  def bar; "bar"; end
 
  count_calls_to :foo
  count_calls_to :bar
 
end

(a snippet of) call_counter_spec.rb:

require "call_foo"
require "spec"
 
describe CallFoo do
 
  before(:each) do
    @call_foo = CallFoo.new
    CallFoo.reset_counters
  end
 
  it "should be able to count several methods' calls" do
    4.times { @call_foo.foo }
    CallFoo.calls_to(:foo).should == 4
    7.times { @call_foo.bar }
    CallFoo.calls_to(:bar).should == 7
  end
 
end

I’m still not 100% content with this solution, the programming interface is nice now but it would be cool to get rid of the class variable somehow, possibly replacing it with closures. If you know how to achieve it, please leave a comment.

ps. You can also get the whole code in nice colored format or the raw text version.

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.

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

by balint

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
Next Page »