【问题标题】:How to return a value on aasm event?如何返回 aasm 事件的值?
【发布时间】:2010-12-10 07:09:33
【问题描述】:

如何使 aasm 事件返回布尔值以外的值?我正在使用aasm 2.2.0

例如有一个 MusicPlayer 模型,它在启动时随机播放一首歌曲

aasm_state :started, :after_enter => :play_song
aasm_state :stopped
aasm_event :start do
  :transitions :from => :stopped, :to => :started
end

def play_song
  # select and play a song randomly and return the song object
end

现在如果我想在启动播放器时返回当前正在播放的歌曲,我该如何通过'play_song'方法呢?

【问题讨论】:

    标签: ruby-on-rails aasm


    【解决方案1】:

    你不能那样做。返回状态用于指示转换是否有问题。但我很好奇你有什么用例需要它。

    但是您可以包装状态转换并使用由play_song 方法设置的变量,如下所示:

    aasm_state :started, :after_enter => :play_song
    aasm_state :stopped
    aasm_event :start do
      :transitions :from => :stopped, :to => :started
    end
    
    def play_song
      # select and play a song randomly
      @song = ...
    end
    
    def shuffle
      if start
        @song
      end
    end
    

    【讨论】:

    • 上面的场景是用例。
    • 嗯,我明白了。您不仅想知道是否正在播放,还想知道播放了什么。这不是一个状态机可以轻易解决的问题。想象一下你有几个回调,例如一个 before_enter 和一个 after_enter 回调。那你会返回哪个结果?我可能会将该逻辑排除在状态机之外并包装状态转换方法。让我根据我的意思更新我的答案。
    • 没错。它实际上更有意义,因为当前歌曲给出了音乐播放器的状态。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 2015-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多