Erudition and Inanity

brian guthrie blogs

The weirdest code I've seen recently

Posted by Brian Guthrie Sat, 02 Aug 2008 22:15:00 GMT

I was kicking around in ActiveResource::Base recently and it took me a good solid ten minutes to figure out why the prefix method didn’t recur infinitely.

def prefix(options={})
  default = site.path
  default << '/' unless default[-1..-1] == '/'
  # generate the actual method based on the current site path
  self.prefix = default
  prefix(options)
end
def prefix_source
  prefix # generate #prefix and #prefix_source methods first
  prefix_source
end
def prefix=(value = '/')
  # Replace :placeholders with '#{embedded options[:lookups]}'
  prefix_call = value.gsub(/:\w+/) { |key| "\#{options[#{key}]}" }
  # Redefine the new methods.
  code = <<-end_code
    def prefix_source() "#{value}" end
    def prefix(options={}) "#{prefix_call}" end
  end_code
  silence_warnings { instance_eval code, FILE, LINE }
rescue
  logger.error "Couldn't set prefix: #{$!}\n  #{code}" 
  raise
end

Do you see it? When prefix is called, it calls prefix=, which redefines prefix and returns. prefix in turn returns by calling not itself but the newly-created method of the same name.

I am not known for my low tolerance of metalanguage hackery (exhibit). But I do have my limits, and this exceeds them; calling it needlessly obfuscatory would be kind. Or am I wrong? Is there no better way to provide a method with the same semantics?

Posted in | 1 comment | Tags , , , , | atom

Trackbacks

Use the following link to trackback from your own site:
http://blog.brianguthrie.com/trackbacks?article_id=the-weirdest-code-ive-seen-recently&day=02&month=08&year=2008

Comments

Leave a response

  1. Yossef about 20 hours later:

    This same sort of shit happens in the routing code, or at least it used to. I remember going through this without the benefit of Jamis’s writeup, and it was ugly.

Leave a comment