问题描述
我正在尝试将一些重复的逻辑分解为 关注.部分重复逻辑是 state_machine.
I am trying to factor out some duplicated logic into a concern. Part of the duplicated logic is a state_machine.
经过简化,Database
、Site
、SftpUser
等包含以下内容:
Simplified, the Database
, Site
, SftpUser
and more contain, amongst others, this:
class Database < ActiveRecord::Base
# ...
state_machine :deploy_state, initial: :halted do
state :pending
end
end
我正在尝试将其重构为一个问题:
I'm attempting to refactor this into a concern:
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_machine
的正确方法,因为这会导致:NoMethodError: undefined method 'deploy_state' for <DeployableDouble:0xb9831f8>
.这表明 Double 根本没有获得分配的状态机.
However, this is not the correct way to implement a state_machnine
in a concern
, because this results in: NoMethodError: undefined method 'deploy_state' for <DeployableDouble:0xb9831f8>
. Which indicates that the Double did not get a statemachine assigned at all.
included do
实际上是实现此功能的正确回调吗?它可能是 state_machine
的问题,它需要一个 ActiveRecord::Base 的子类吗?我没有得到的东西?我对关注的概念还很陌生.
Is the included do
actually the right callback to implement this? Is it maybe an issue with state_machine
, it needing a subclass of ActiveRecord::Base or so? Something I'm not getting? I am pretty new to the concept of Concerns.
推荐答案
好的.我真的觉得自己很蠢.不应该extend
一个带有模块的类,而是include
那个模块.很明显.
Okay. I am feeling really stupid. One should not extend
a class with a module, but include
that module. Obviously.
# Tested with:
class DeployableDouble
include Deployable
end
一旦写完,你就监督其中的一件事情.此外,不需要扩展 ActiveRecord::Base
,因为 state_machine 只是普通的旧 Ruby 并且适用于通用 Ruby 对象.
One of these things that you oversee once written. Also, extending the ActiveRecord::Base
is not needed, since state_machine is just plain old Ruby and works on a generic Ruby Object.
这篇关于如何在关注点中定义 state_machine?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!