ber*_*kes 4 state-machine ruby-on-rails-4 activesupport-concern
我试图将一些重复的逻辑分解为一个问题.部分重复逻辑是state_machine.
简化的Database,Site,SftpUser多包含,除其他外,这样的:
class Database < ActiveRecord::Base
# ...
state_machine :deploy_state, initial: :halted do
state :pending
end
end
Run Code Online (Sandbox Code Playgroud)
我试图将此重构为一个问题:
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
Run Code Online (Sandbox Code Playgroud)
但是,这不是在a state_machnine中实现a的正确方法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
Run Code Online (Sandbox Code Playgroud)
一旦写完你就会监督的其中一件事.此外,ActiveRecord::Base不需要扩展,因为state_machine只是普通的旧Ruby,适用于通用的Ruby对象.