问题描述
我在理解这段代码中alias_method的目的时遇到了麻烦
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
第4行调用configure_connection_without_interval
的目的是什么-不仅仅是调用自身吗?
下面的代码对我有用,但是我不完全知道自己在做什么,我担心它以后会产生错误。
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.class_eval do
define_method :configure_connection do
execute('SET intervalstyle = iso_8601','SCHEMA')
end
end
解决方法
alias_method
在重新定义方法之前立即在该行上操作,并以该给定名称保留旧方法。
这是一种通用的Ruby技术,用于捕获特定方法的一个版本并将其包装在另一个方法中。当您直接修补类而不是子类时,通常会被迫这样做。