LoginSignup
0
0

More than 1 year has passed since last update.

#Ruby の AASM って何? Rails じゃなくても使えるの? 使えるよ!

Last updated at Posted at 2019-11-06

それだけ。以上。

gem

aasm/aasm: AASM - State machines for Ruby classes (plain Ruby, ActiveRecord, Mongoid)

いろいろな ORM にアダプタとして使われてるけど、どんなRuby Classでも使えるって書いてる気がするよ。

This package contains AASM, a library for adding finite state machines to Ruby classes.
AASM started as the acts_as_state_machine plugin but has evolved into a more generic library that no longer targets only ActiveRecord models. It currently provides adapters for many ORMs but it can be used for any Ruby class, no matter what parent class it has (if any).

コードと動作例

require 'aasm'

class Job
  include AASM

  aasm do
    state :sleeping, initial: true
    state :running, :cleaning

    event :run do
      transitions from: :sleeping, to: :running
    end

    event :clean do
      transitions from: :running, to: :cleaning
    end

    event :sleep do
      transitions from: [:running, :cleaning], to: :sleeping
    end

    after_all_transitions :log_status_change
  end

  def log_status_change
    puts "changing from #{aasm.from_state} to #{aasm.to_state} (event: #{aasm.current_event})"
  end
end
job = Job.new
# => #<Job:0x00007fb0d9f80750>

job.run
# => changing from sleeping to running (event: run)

なんでDBがなくても動くの?

DBなんてなくても状態は保持できるからだよ。要するにメモリね。うん。

考えてみれば当たり前だよね。

Original by Github issue

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0