Sha256: 4a3dbd3aaa3934604b708845d853b32c10748cb59938a08a3242d5a93fd59071

Contents?: true

Size: 1.71 KB

Versions: 2

Compression:

Stored size: 1.71 KB

Contents

# frozen_string_literal: true

require 'repository/support/error_factory'
require 'repository/support/store_result'

module Repository
  # Base class for Repository in Data Mapper pattern.
  class Base
    # Internal support code exclusively used by Repository::Base
    module Internals
      # Reports on the success or failure of saving a *DAO record*, using the
      # `Repository::Support::StoreResult` instance returned from `#result`.
      # @since 0.0.1
      class RecordSaver
        include Repository::Support

        # Sets instance variable(s) on a new `RecordSaver` instanace.
        # @param record DAO record to attempt to save.
        def initialize(record:, factory:)
          @record = record
          @factory = factory
        end

        # Command-pattern method returning indication of success or failure of
        # attempt to save record.
        # @return Repository::Support::StoreResult
        # @see #failed_result
        # @see #successful_result
        def result
          if record.save
            successful_result
          else
            failed_result
          end
        end

        private

        attr_reader :factory, :record

        # Represent error data sourced from an `ActiveModel::Errors` object as
        # an Array of `{field: 'field', message: 'message'}` hashes.
        def error_hashes
          ErrorFactory.create record.errors
        end

        def failed_result
          StoreResult::Failure.new error_hashes
        end

        def successful_result
          entity = factory.create record
          StoreResult::Success.new entity
        end
      end # class Internals::RecordSaver
    end # module Repository::Base::Internals
  end # class Repository::Base
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
repository-base-0.4.1 lib/repository/base/internals/record_saver.rb
repository-base-0.4.0 lib/repository/base/internals/record_saver.rb