I’ve moved!

This blog has moved to www.mrrubato.com.


January 27, 2009. Uncategorized. Leave a comment.

Formatting source code in wordpress.com blogs

I just found out that there’s a way to format source code in wordpress.com blogs without having to mess around with the HTML yourself. You just need to surround your code with a tag.

From http://support.wordpress.com/code/:

Code in between the tags will automatically be encoded for display, you don’t need to worry about HTML entities or anything.

When I get the chance, I’ll go through the old entries and modify them to make use of this feature.

January 19, 2009. Tags: . Uncategorized. Leave a comment.

Overloading the ActiveRecord Setter

Sometimes, you want to do some extra work when you set an attribute on your ActiveRecord model instance.

You can’t just do this, because you’ll just end up recursively calling the very setter that you’re defining:

class Square < ActiveRecord::Base
    def side=(value)
        self.area = value*value
        self.side = value
<div>...and you can't do this because you'll end up modifying a copy of the attributes hash of the model instance, which will not be written through to the database when the model instance is saved ( check out ActiveRecord::Base::attributes in active_record/base.rb):</div>

class Square &gt; ActiveRecord::Base
    def side=(value)
        self.attributes['side'] = value
        self.area = value * value
After looking through the source for ActiveRecord::Base and some testing, I’ve found a method that’s worked for me and appears to be the preferred way of doing it:
class Square &gt; ActiveRecord::Base
    def side=(value)
        self.area = value * value # This would still work because we're calling the default setter for area
        write_attribute('side', value)
Alternatively, you could do “self[‘side’] = value” instead of write_attribute.   The index assignment operatore actually does the same thing.

January 13, 2009. Tags: . Uncategorized. Leave a comment.

Monkey business and how to track monkey-patching of classes in Ruby

To celebrate my 2 month anniversary with Ruby, I thought I’d play around a bit with its metaprogramming features. A quick intro: Ruby supports what some simian-primate aficionados would call monkey-patching.

Monkey patching is a way to extend or modify the runtime code of dynamic languages (e.g. Smalltalk, Javascript, Objective-C, Ruby, Perl, Python, Groovy etc.) without altering the original source code.

One way to do this in Ruby is by taking advantage of the fact that it supports “open classes.” That means that you can re-define parts of the class after it has already been defined. For example, you would be able to add a new to_s method to a class by doing the following:

class AwesomeClass
    def initialize(value)
        @value = value
    def to_s

ac = AwesomeClass.new("Soggy bacon")

puts ac # prints "Soggy bacon" 

# Change AwesomeClass's to_s implementation 
# who likes soggy bacon?)
class AwesomeClass
    def to_s
        "Chunky bacon!"

puts ac # prints "Chunky bacon!"

In Ruby, all classes are simply instances of the Class type.  Whenever you define a method on a class, the Class instance’s method_added method is called with the name of the method being defined.  For example, if we did the following, String.method_added() would be called with “l33ticize” as the argument:

class String
   def l33ticize
       # l33ticize the string - left as        
       # exercise for the reader...that's        
       # you! :)

Monkeys Watching Monkeys

By using open classes, we can re-define method_added for instances of Class and do some custom stuff every time a method is defined for any class.  In this example, we’re re-defining method_added so that it tracks where the method was last defined.

#!/usr/bin/env ruby                                                                                                                                                           

class Class
  @@method_history = {}

  def self.method_history
    return @@method_history

  def method_added(method_name)
    puts "#{method_name} added to #{self}"
    @@method_history[self] ||= {}
    @@method_history[self][method_name] = caller

  def method_defined_in(method_name)
    return @@method_history[self][method_name]

class SomeClass
  attr_accessor  :value
  def initialize(value)
    @value = value

  def compute
    return @value * 2

s = SomeClass.new(10)

puts s.compute # Prints "20"

# Prints this file + line number from 
# the @value * 2 definition
p SomeClass.method_defined_in(:compute)
class SomeClass
  def compute
    return @value * 3

puts s.compute # Prints "30"

# Prints this file + line number from
# the @value * 3 definition
p SomeClass.method_defined_in(:compute)

For more fun…

Comments are welcome.  There are definitely cleaner ways to implement the above.  For example, instead of storing an @@method_history variable on Class, you could store it for each Class instance (e.g. SomeClass.method_history).

What kinds of style guidelines should one follow when doing these kinds of things?  Was it a good choice to use open classes instead of using class_eval, send, or even instance_eval?  I don’t really have the answer right now, but it’s definitely on my list of things to think about while I brush my teeth in the mornings.

If anyone’s out there, I invite you to do any of the following:

  • Implement the l33ticize method
  • Improve on the method_defined_in implementation

November 27, 2008. Tags: , . Uncategorized. Leave a comment.

Ruby load path

There are three ways to refer to the variable that stores the load paths that Ruby checks for libraries when you use ‘require’ or ‘load.’

$:, $-I, $LOAD_PATH

November 20, 2008. Tags: . Uncategorized. Leave a comment.

19 Rails Tricks

I came across this article on Ruby Inside. It contains a nice quick list of things that you might not have known that you can do in Rails.  I find the Rails Engines to be particularly interesting.


  1. Benchmark logic in your controller actions
  2. acts_as_nested_set
  3. Easier collections with to_proc
  4. Convert arrays to sentences in views
  5. Send files back to the user
  6. Iterating through page elements with RJS
  7. Check for existence
  8. Number helpers for common number tasks
  9. Testing different route configurations easily
  10. Get lots of info about requests
  11. Improving session performance even more than with ActiveRecord
  12. Caching unchanging data at application startup
  13. Check your views are rendering valid HTML / XHTML
  14. Cleaner HTML output testing 
  15. Run long-running tasks separately in the background
  16. Make ids in URLs more user friendly
  17. Separate out slices of functionality into Engines
  18. Calculations
  19. XML or YAML output of your data 

November 18, 2008. Tags: . Uncategorized. Leave a comment.

Advanced Python

November 9, 2008. Tags: . Uncategorized. Leave a comment.

Which process is using that port?

A simple example: to find out which process is using TCP port 8080

$ fuser -n tcp 8080

October 27, 2008. Tags: , , . Uncategorized. Leave a comment.

How to delete a remote branch from a git repository

This isn’t obvious, so I thought I’d post an example for deleting a remote branch.

Let’s say you want to delete origin/some_branch from origin

$ git branch -a
* master

To remove the branch, just do this:

$ git push origin :some_branch

Now, it’s gone!

$ git branch -a
* master

From the git push manual page:

The canonical format of a <refspec> parameter is +?<src>:<dst>; that is, an optional plus +, followed by the source ref, followed by a colon :, followed by the destination ref.

Pushing an empty <src> allows you to delete the <dst> ref from the remote repository.

So, when you do “git push repo src:dest”, that translates to “git push <repository> <refspec>”.  In the example above, <repository> was “origin” and <refspec> was “:some_branch”.  Since there was no <src> part of the refspec, the <dst> ref was deleted from the remote repository.

October 24, 2008. Tags: . Uncategorized. Leave a comment.

I’m a PC

This I’m a PC ad campaign is way better than the Seinfeld one that was cut so quickly last month.

Joe Wilcox at microsoft-watch sums it up:

Overall, the commercials are endearing. I like them more than I expected. But their shortcoming is the same as the Bill and Jerry ads: The commercials don’t say much about Windows. In that sense, Apple set the agenda by using PC to identify Windows.

Yes! They’re endearing!  The commercials imply that there are tons of PC users out there who don’t feel the need to make a loud statement about how they’re different because of their operating system and just go about their lives.  Who would you rather be, the Mac hipster depicted by Justin Long, or one everyday people from all walks of life-fishermen, students, taxi drivers, artists and scientists-shown on the PC ads?

October 21, 2008. Tags: , , . technology, Uncategorized. Leave a comment.

Next Page »