Could someone help me understand what alias_method does in this code

Viewed 33

I'm having trouble understanding the purpose of alias_method in this code

ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.class_eval do
  alias_method :configure_connection_without_interval, :configure_connection
  define_method :configure_connection do
    configure_connection_without_interval
    execute('SET intervalstyle = iso_8601', 'SCHEMA')
  end
end

What is the purpose of line 4 where they call configure_connection_without_interval -- doesn't that just call itself?

The code below works for me but I don't fully know what I'm doing and I'm worried it'll create bugs later

ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.class_eval do
  define_method :configure_connection do
    execute('SET intervalstyle = iso_8601', 'SCHEMA')
  end
end
1 Answers

alias_method operates immediately on that line before the method is redefined, preserving the old method under that given name.

That's a common Ruby technique to capture a version of a particular method and wrap it in another. When you're patching a class directly instead of subclassing you'll often be forced to do this.

Related