我试图因素出一些双重逻辑成关注。复制逻辑的一部分是state_machine。
简化的Database
,Site
,SftpUser
多包含,除其他外,这样的:
class Database < ActiveRecord::Base
# ...
state_machine :deploy_state, initial: :halted do
state :pending
end
end
我试图将其重构为一个问题:
module Deployable
extend ActiveSupport::Concern
included do
state_machine :deploy_state, initial: :halted do
state :pending
end
end
end
# Tested with:
class DeployableDouble < ActiveRecord::Base
extend Deployable
end
describe DeployableDouble do
let(:subject) { DeployableDouble.new }
it "should have default state halted" do
subject.deploy_state.must_equal "halted"
end
end
然而,这不是实行正确的方法state_machnine
在concern
,因为这会导致:NoMethodError: undefined method 'deploy_state' for <DeployableDouble:0xb9831f8>
。这表明Double根本没有分配状态机。
是included do
真正实现这个正确的回调?可能是的问题state_machine
,它需要ActiveRecord :: Base的子类左右吗?我没有得到什么?我对关注的概念非常陌生。
好的。我真的很傻。一个不应该extend
带有模块的类,而是include
那个模块。明显地。
# Tested with:
class DeployableDouble
include Deployable
end
一旦写完,您将监督这些事情之一。另外,ActiveRecord::Base
不需要扩展,因为state_machine只是普通的旧Ruby,并且可以在通用Ruby Object上工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句