The weirdest code I've seen recently
2008-08-02 08:15:00 -0400I 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?