Skip to content

Instantly share code, notes, and snippets.

@tasdikrahman
Forked from danielfone/aasm_after_commit.rb
Created August 4, 2020 07:00
Show Gist options
  • Select an option

  • Save tasdikrahman/07c185f15608ca0050cd6d27ed27b9d6 to your computer and use it in GitHub Desktop.

Select an option

Save tasdikrahman/07c185f15608ca0050cd6d27ed27b9d6 to your computer and use it in GitHub Desktop.

Revisions

  1. @danielfone danielfone revised this gist Jul 16, 2015. 1 changed file with 14 additions and 2 deletions.
    16 changes: 14 additions & 2 deletions aasm_after_commit.rb
    Original file line number Diff line number Diff line change
    @@ -2,9 +2,19 @@
    # activerecord 4.2.3
    # aasm 4.2.0

    require_relative 'setup_active_record'
    require 'active_record'
    require 'aasm'

    # Setup a mock AR table
    ActiveRecord::Migration.verbose = false
    ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
    ActiveRecord::Schema.define(:version => 1) do
    create_table :orders do |t|
    t.string :aasm_state
    end
    end

    # Example record with scope
    class Order < ActiveRecord::Base
    include AASM

    @@ -23,9 +33,11 @@ def log_placed
    end

    o = Order.create!

    ActiveRecord::Base.logger = Logger.new(STDOUT)

    #
    # The behaviour under question starts here
    #
    Order.transaction do
    o.place!
    raise ActiveRecord::Rollback
  2. @danielfone danielfone renamed this gist Jul 16, 2015. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  3. @danielfone danielfone created this gist Jul 16, 2015.
    43 changes: 43 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    # ruby 2.2.2
    # activerecord 4.2.3
    # aasm 4.2.0

    require_relative 'setup_active_record'
    require 'aasm'

    class Order < ActiveRecord::Base
    include AASM

    aasm do
    state :draft, initial: true
    state :placed

    event :place, after_commit: :log_placed do
    transitions from: :draft, to: :placed
    end
    end

    def log_placed
    logger.info "Order has been placed"
    end
    end

    o = Order.create!

    ActiveRecord::Base.logger = Logger.new(STDOUT)

    Order.transaction do
    o.place!
    raise ActiveRecord::Rollback
    end
    o.reload
    o.logger.info o.aasm_state

    # DEBUG -- : (0.1ms) begin transaction
    # DEBUG -- : (0.0ms) SAVEPOINT active_record_1
    # DEBUG -- : SQL (0.1ms) UPDATE "orders" SET "aasm_state" = ? WHERE "orders"."id" = ? [["aasm_state", "placed"], ["id", 1]]
    # DEBUG -- : (0.0ms) RELEASE SAVEPOINT active_record_1
    # INFO -- : Order has been placed
    # DEBUG -- : (0.0ms) rollback transaction
    # DEBUG -- : Order Load (0.1ms) SELECT "orders".* FROM "orders" WHERE "orders"."id" = ? LIMIT 1 [["id", 1]]
    # INFO -- : draft