Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

それだけ。以上。

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

https://github.com/YumaInaura/YumaInaura/issues/2673

YumaInaura
Ruby on Rails 業務経験 約5年 / Perl PHP Python Golang Linux Apache MySQL BigQuery Jenkins ansible AWS など / いなうらゆうま / YumaInaura / 稲浦悠馬
http://twitter.com/yumainaura
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away