不能在模块中包含 state_machine
Can't include state_machine in module
我正在尝试在两个模型中使用一个状态机并让它们在一个模块中共享它
module Schedulable
state_machine :state, initial: :unscheduled
end
class Install < ActiveRecord::Base
include Schedulable
end
我收到以下错误
NameError: undefined local variable or method `state_machine' for Schedulable:Module
如何正确地包含模块中的状态机?我使用的是 state_machines
gem
的最新版本
下面的 class 说明了如何通过调用 class 之外的方法向 class 添加行为。您需要将方法定义替换为具有状态机代码的定义。
#!/usr/bin/env ruby
module ModifyClass
def self.add_foo_class_method(klass)
class << klass
def foo
puts 'I am foo.'
end
end
end
end
class C
ModifyClass.add_foo_class_method(self)
end
C.foo # => "I am foo."
为了更符合您的上下文,我认为它可能看起来像这样:
module StateMachineAdder
def self.add(klass)
class << klass
# state_machine ...
end
end
end
class MyModel_1
StateMachineAdder.add(self)
end
class MyModel_2
StateMachineAdder.add(self)
end
或者,您可以在 class 中定义常见行为(例如在 class 定义中对 state_machine 的调用,以及包含相同或相同的两个模型中的方法大多数相同的行为),然后让你的 2 个模型子 class 那个 class。这很可能是最简单的解决方案。例如:
class XyzModelBase
state_machine ...
# Any methods common to both base classes can go here
def foo
# ...
end
end
class XyzModelFoo < XyzModelBase
# ...
end
class XyzModelBar < XyzModelBase
# ...
end
#
状态机依赖于 ActiveRecord 模型,所以你需要制作像 concerns 这样的模块。
module Schedulable
extend ActiveSupport::Concern
included do
state_machine :state, initial: :unscheduled
end
end
我正在尝试在两个模型中使用一个状态机并让它们在一个模块中共享它
module Schedulable
state_machine :state, initial: :unscheduled
end
class Install < ActiveRecord::Base
include Schedulable
end
我收到以下错误
NameError: undefined local variable or method `state_machine' for Schedulable:Module
如何正确地包含模块中的状态机?我使用的是 state_machines
gem
下面的 class 说明了如何通过调用 class 之外的方法向 class 添加行为。您需要将方法定义替换为具有状态机代码的定义。
#!/usr/bin/env ruby
module ModifyClass
def self.add_foo_class_method(klass)
class << klass
def foo
puts 'I am foo.'
end
end
end
end
class C
ModifyClass.add_foo_class_method(self)
end
C.foo # => "I am foo."
为了更符合您的上下文,我认为它可能看起来像这样:
module StateMachineAdder
def self.add(klass)
class << klass
# state_machine ...
end
end
end
class MyModel_1
StateMachineAdder.add(self)
end
class MyModel_2
StateMachineAdder.add(self)
end
或者,您可以在 class 中定义常见行为(例如在 class 定义中对 state_machine 的调用,以及包含相同或相同的两个模型中的方法大多数相同的行为),然后让你的 2 个模型子 class 那个 class。这很可能是最简单的解决方案。例如:
class XyzModelBase
state_machine ...
# Any methods common to both base classes can go here
def foo
# ...
end
end
class XyzModelFoo < XyzModelBase
# ...
end
class XyzModelBar < XyzModelBase
# ...
end
#
状态机依赖于 ActiveRecord 模型,所以你需要制作像 concerns 这样的模块。
module Schedulable
extend ActiveSupport::Concern
included do
state_machine :state, initial: :unscheduled
end
end