Module: Komando::Persistence::ActiveRecord

Defined in:
lib/komando/persistence/active_record.rb

Overview

Wraps command executions within a database transaction.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object

Insinuates this module within Command.



12
13
14
# File 'lib/komando/persistence/active_record.rb', line 12

def self.included(base)
  base.send :alias_method_chain, :run!, :transaction
end

Instance Method Details

#loggerObject

Uses the same Logger instance as ActiveRecord.



59
60
61
# File 'lib/komando/persistence/active_record.rb', line 59

def logger
  ::ActiveRecord::Base.logger
end

#run_with_transaction!Object

Wraps a command execution within a database transactions. This method delegates actual transaction semantics to #wrap_transaction. This method is renamed as Command##run! during inclusion.



19
20
21
22
23
# File 'lib/komando/persistence/active_record.rb', line 19

def run_with_transaction!
  wrap_transaction do
    run_without_transaction!
  end
end

#wrap_transactionObject

Does the actual work of wrapping in a transaction. The default is to wrap using ActiveRecord::Base#transaction.

Examples:

Wrapping using a specific connection

# config/database.yml
development:
  adapter: sqlite3
  database: db/development.sqlite3

require "komando/persistence/active_record"

class User < ActiveRecord::Base
  establish_connection :adapter => "sqlite3", :database => "/var/dbs/users.sqlite3"
end

class CreateUserCommand
  include Komando::Command
  include Komando::Persistence::ActiveRecord

  def wrap_transaction
    User.transaction do
      yield
    end
  end
end

Yield Returns:

  • The block’s last value.



52
53
54
55
56
# File 'lib/komando/persistence/active_record.rb', line 52

def wrap_transaction
  ::ActiveRecord::Base.transaction do
    yield
  end
end