Fork me on GitHub

From Siberia with love

WTFrb

I’ve never understood why Ruby so inconsistent relative to bang methods. Not every method which modifies object in place has “!” mark.

A couple of monthes ago I found strange bug in my project. There is similar example code:

require 'excon'

class Storage
  def initialize
    @storage = Excon.new('https://pbs.twimg.com/')
  end

  def get_file(path)
    @storage.request(path: path)
  end
end

path = 'media/BHTpMe4CUAA1oR9.jpg'

storage = Storage.new
storage.get_file(path)

puts path
# => /media/BHTpMe4CUAA1oR9.jpg
# WAT

WTF! I opened excon source code and looked into request method:

def request(params={}, &block)
  <..>
  # if path is empty or doesn't start with '/', insert one
  unless datum[:path][0, 1] == '/'
    datum[:path].insert(0, '/')
  end
  <..>
end

Here you are! The reason is that String#insert method modifies object instead of returning copy (the same for #replace, #prepend).

P.S. At the moment this behaviour fixed in master.

blog comments powered byDisqus