在Bryan Helmkamp的优秀博客文章" 7个模式来重构Fat ActiveRecord模型 "中,他提到使用Form Objects抽象多层形式并停止使用accepts_nested_attributes_for.
编辑:请参阅下面的解决方案.
我几乎完全复制了他的代码示例,因为我有同样的问题需要解决:
class Signup
include Virtus
extend ActiveModel::Naming
include ActiveModel::Conversion
include ActiveModel::Validations
attr_reader :user
attr_reader :account
attribute :name, String
attribute :account_name, String
attribute :email, String
validates :email, presence: true
validates :account_name,
uniqueness: { case_sensitive: false },
length: 3..40,
format: { with: /^([a-z0-9\-]+)$/i }
# Forms are never themselves persisted
def persisted?
false
end
def save
if valid?
persist!
true
else
false
end
end
private
def persist!
@account = …Run Code Online (Sandbox Code Playgroud) 我正在从Rails 2.x到3.x重写/重构客户端的遗留应用程序.作为重构的一部分,我还想从我们的本地语言中的模型/方法转向纯粹的英语代码库.
这涉及为几乎每个功能编写新方法.我通过这样做解决方法:
def english_method
# ...
end
def native_method
warn 'DEPRECATED, please use #english_method'
english_method
end
Run Code Online (Sandbox Code Playgroud)
这适用于方法,并帮助我跟踪旧方法仍在使用的地方,而不会破坏任何代码.
然而,对于类(模型),我一直在做:
class NativeClass < EnglishClass
# DEPRECATED, Please use EnglishClass
end
class EnglishClass
# ...
end
Run Code Online (Sandbox Code Playgroud)
这个"工作",无论什么时候NativeClass被调用,应用程序都会继续工作,但我没有在日志中收到任何消息,通知我应用程序的一部分仍在调用NativeClass.
如何确保每次"触摸" NativeClass实际上都会导致写入日志错误?
我试过(除了认为"可能这样有效"之外),这样做:
class NativeClass < EnglishClass
-> { ActiveSupport::Deprecation.warn 'Native model is deprecated in favor of English' }
end
Run Code Online (Sandbox Code Playgroud)
但那(显然?)没有用.我认为每次NativeClass调用lambda都会延迟加载,但是我对lambdas的理解仍然有些浅薄,所以我可能会在这里弄错.
有关如何弃用整个类并在触摸时向我的日志发送警告消息的任何线索?
其他"最佳实践"和/或弃用解决方案是受欢迎的,但我不确定它是否是SO的有效问题(我不想冒这个问题关闭这个问题的风险).