Ruby recipie: extending methods without loose the original code

Supose you want to extend the method of a class called Attachment.

# original_file.rb

class Attachment
  def method_to_extend
    puts "The original code"
  end
end

If we try to rewrite the method, older code gets lost, but instead we want it to be executed with our code extension

We want to achieve something like the following:

class Attachment
  def method_to_extend
    puts "The original code"
    puts "My extension code!"
  end
end

But the original code is part of a library we cannot change directly.

The best way I found is to write an alias_method with the original method code and rewrite the method adding the desired code

# extension_file.rb

require 'original_file'
class Attachment
  alias_method :source_method_to_extend, :method_to_extend
  def method_to_extend
    source_method_to_extend
    puts "My extension code!"
  end
end