Techioz Blog

プロミスの概念は Ruby で利用できますか?

概要

ちょっと疑問に思っているのですが、Ruby には連鎖の概念があるのでしょうか。 一連の非同期タスクまたはメソッドを次々に実行したいと考えていました。出来ますか?

解決策

次のようなプロセス クラスを作成するとよいでしょう。

class MyProcess

  PROCESS_STEPS = %w(
    step_one
    step_two
    step_three
  )

  class << self 

    def next_step
      new.next_step
    end

  end # Class Methods

  #======================================================================
  # Instance Methods
  #======================================================================

    def next_step
      PROCESS_STEPS.each do |process_step|
        send(process_step) if send("do_#{process_step}?")
      end
    end

    def step_one
      # execute step one task
    end

    def do_step_one?
      # some logic
    end

    def step_two
      # execute step two task
    end

    def do_step_two?
      # some logic
    end

    def step_three
      # execute step three task
    end

    def do_step_three?
      # some logic
    end

end

おそらく次のように入れるでしょう。

app 
 |- processes
 |   |- my_process.rb

次に、各タスクの最後に次のようなことを行います。

MyProcess.next_step