Module: Shamu::Services::ActiveRecord

Defined in:
lib/shamu/services/active_record.rb

Overview

Helper methods useful for services that interact with ActiveRecord::Base models.

Instance Method Summary collapse

Instance Method Details

#scope_relation(relation, list_scope) ⇒ ActiveRecord::Relation

Apply the filters specified in list_scope to the relation.

Parameters:

  • relation (ActiveRecord::Relation)

    to filter.

  • list_scope (Entities::ListScope)

    to apply.

Returns:

  • (ActiveRecord::Relation)

    the scoped relation.



46
47
48
49
50
51
52
53
54
# File 'lib/shamu/services/active_record.rb', line 46

def scope_relation( relation, list_scope )
  return unless relation

  if relation.respond_to?( :by_list_scope )
    relation.by_list_scope( list_scope )
  else
    fail "Can't scope a #{ relation.klass }. Add `scope :by_list_scope, ->(list_scope) { ... }` or extend Shamu::Entities::ActiveRecord." # rubocop:disable Metrics/LineLength
  end
end

#with_transaction(options = {}, &block) ⇒ Result

Wrap all the changes to any ActiveRecord resource in a transaction.

Parameters:

  • options (Hash) (defaults to: {})

    to pass to ActiveRecord::Transactions.transaction.

Yield Returns:

  • (Result)

    the validation sources for the transaction. See Service#with_result.

Returns:



28
29
30
31
32
33
34
35
36
37
# File 'lib/shamu/services/active_record.rb', line 28

def with_transaction( options = {}, &block )
  result = nil

  ::ActiveRecord::Base.transaction options do
    result = yield
    raise ::ActiveRecord::Rollback if result && !result.valid?
  end

  result
end

#wrap_not_found(&block) ⇒ Object

Watch for ActiveRecord::RecordNotFound errors and rethrow as a NotFoundError.



14
15
16
17
18
# File 'lib/shamu/services/active_record.rb', line 14

def wrap_not_found( &block )
  yield
rescue ::ActiveRecord::RecordNotFound
  raise Shamu::NotFoundError
end