Sha256: 40533c7c9c2c3539aab7ab154855acdea9b7c3716d537dd38132ec508859cd61

Contents?: true

Size: 1.91 KB

Versions: 3

Compression:

Stored size: 1.91 KB

Contents

# frozen_string_literal: true

module ROM
  class Changeset
    # Changeset specialization for update commands
    #
    # Update changesets will only execute their commands when
    # the data is different from the original tuple. Original tuple
    # is fetched from changeset's relation using `one` method.
    #
    # @example
    #   users.by_pk(1).changeset(:update, name: "Jane Doe").commit
    #
    # @see Changeset::Stateful
    #
    # @api public
    class Update < Stateful
      command_type :update

      # Commit update changeset if there's a diff
      #
      # This returns original tuple if there's no diff
      #
      # @return [Hash]
      #
      # @see Changeset#commit
      #
      # @api public
      def commit
        diff? ? super : original
      end

      # Return original tuple that this changeset may update
      #
      # @return [Hash]
      #
      # @api public
      def original
        @original ||= relation.one
      end

      # Return true if there's a diff between original and changeset data
      #
      # @return [TrueClass, FalseClass]
      #
      # @api public
      def diff?
        !diff.empty?
      end

      # Return if there's no diff between the original and changeset data
      #
      # @return [TrueClass, FalseClass]
      #
      # @api public
      def clean?
        diff.empty?
      end

      # Calculate the diff between the original and changeset data
      #
      # @return [Hash]
      #
      # @api public
      def diff
        @diff ||=
          begin
            source = Hash(original)
            data = pipe.for_diff(__data__)
            data_tuple = data.to_a
            data_keys = data.keys & source.keys

            new_tuple = data_tuple.to_a.select { |k, _| data_keys.include?(k) }
            ori_tuple = source.to_a.select { |k, _| data_keys.include?(k) }

            Hash[new_tuple - (new_tuple & ori_tuple)]
          end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rom-changeset-5.3.0 lib/rom/changeset/update.rb
rom-changeset-5.2.3 lib/rom/changeset/update.rb
rom-changeset-5.2.1 lib/rom/changeset/update.rb