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

ivqmmu1c  于 2023-05-22  发布在  Ruby
关注(0)|答案(2)|浏览(177)
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'

sc4hvdpw

sc4hvdpw1#

首先,!:cancelled?表达式的计算结果总是false,因此在这种情况下aasm甚至不会调用cancelled?方法。为了减少代码量,你可以像下面这样

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

u91tlkcl2#

在较新版本的AASM中,您可以使用unless语法来避免定义单独的not_cancelled方法:

transitions from: :new, to: :open, unless: :cancelled?

相关问题