Objects to Ruby code (rrepr)
Posted by Kevin
Python has a useful function called repr, which takes an object and returns a string with valid Python code for reproducing that object.
Example:
>>> a = [1, 2, 3] >>> repr(a) '[1, 2, 3]'
Ruby, however, has no such function built in. After running into a couple of problems where we wished we could use repr (more on those later), we decided to roll our own.
We chose the name rrepr (Ruby repr) and started defining it as an instance method on classes of interest. In some cases this is very simple.
class String def rrepr; inspect end end
In others it’s a little more complex.
class Hash
def rrepr
'{' + map{|k,v| k.rrepr + '=>' + v.rrepr}.join(', ') + '}'
end
end
In the end though, all of the basic classes end up being pretty easy to define. What about more complex classes?
The general problem is very hard; Python’s repr only really works for basic types like strings and arrays. However, it turns out that in Rails, an extremely large percentage of the objects we care about are ActiveRecord objects, and for those the find method makes it dirt simple:
class ActiveRecord::Base
def rrepr; "#{self.class.rrepr}.find(#{id.rrepr})" end
end
Its surprising how often this comes in handy. Stay tuned for some examples.