使用Ruby gem aasm,是否可以在返回布尔结果的保护函数上定义not(!)运算符?

时间:2014-03-29 18:27:58

标签: ruby-on-rails ruby aasm

class Ticket
  include AASM

  state :new
  state :open
  state :closed

  event :open do
    transitions :from => :new,:to => :closed, :guard => :cancelled?
    transitions :from => :new,:to => :open, :guard => !:cancelled?
  end
  def cancelled?
    true
  end
  def not_cancelled?
    true
  end
end

##Would I need the below?
transitions :from => :new,:to => :open, :guard => :not_cancelled?

为了减少我必须编写的代码量,是否有可能在保护功能中取消!:取消?或者我是否必须单独写一个not_cancelled?功能(我怀疑是这样的)。

我使用Ruby 2.1与gem' aasm','〜> 3.1.1'

1 个答案:

答案 0 :(得分:1)

首先,!:cancelled?表达式总是评估为false,因此在这种情况下,aasm甚至不会调用cancelled?方法。要减少代码量,可以使用以下代码

transitions :from => :new, :to => :closed, :guard => :cancelled?
transitions :from => :new, :to => :open, :guard => Proc.new { |ticket| !ticket.cancelled? }