我最近不得不在我的一个应用程序中扩展最新版本的restful_authentication(github)的aasm状态。我删除了“include Authorization :: AasmRoles”,从插件复制了现有的状态和事件,并进行了必要的更改以支持额外的“已发布”状态。在我的帐户模型上陈述。

有没有人有更清洁的方法来处理这个问题?即只是覆盖状态事件?我能够按原样使用插件添加新事件,但是我无法仅覆盖restful_auth中已有的状态事件,因此我必须删除include并将其作为起点自行写出来。

有帮助吗?

解决方案

在AASM中添加状态包括创建一个新的State对象,然后将其添加到AASM :: StateMachine [User] .states数组中,如下所示:

def create_state(name, options)
 @states << AASM::SupportingClasses::State.new(name, options) unless @states.include?(name)
end

这里需要注意的是,一旦设置状态,它将不允许覆盖状态。如果再次设置具有相同名称的状态,则create_state方法只会忽略它。要解决此问题,您可以在用户模型中使用类似的内容:

# this will remove the state with name :name from the states array 
states = AASM::StateMachine[self].states
states.delete(states.find{ |s| s == :name })
# ... so we can define the state here again
aasm_state :name ...

如果你只是重新定义国家,你现在应该没事。但是如果你想完全删除状态,你也应该取消定义aasm_state方法体中定义的方法。调用类似的东西应该是可能的:

undef_method :name

情况应该与事件相同(只是在代码中使用“事件”而不是“状态”)。理想情况下,使用户模型的类方法覆盖AASM模块中定义的方法。对于状态,它看起来像这样:

def aasm_state(name, options={})
  states = AASM::StateMachine[self].states
  states.delete(states.find{ |s| s == name.to_sym })
  super(name, options)
end

警告:我可能不对。这段代码未经测试,我只是通过查看AASM的源代码来解决它。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top