Class: ROM::Changeset::Update

Inherits:
Stateful show all
Defined in:
lib/rom/changeset/update.rb

Overview

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.

Examples:

users.by_pk(1).changeset(:update, name: "Jane Doe").commit

See Also:

Constant Summary

Constants inherited from Stateful

Stateful::EMPTY_PIPE

Instance Attribute Summary

Attributes inherited from Stateful

#__data__, #pipe

Attributes inherited from ROM::Changeset

#command_options, #command_plugins, #command_type, #relation

Instance Method Summary collapse

Methods inherited from Stateful

#associate, #command_compiler_options, #data, default_pipe, extend, #extend, inherited, #inspect, map, #map, pipes, #result, #to_a, #to_h

Methods inherited from ROM::Changeset

[], #command, #command_compiler_options, command_options, command_plugins, command_type, #inspect, #new, relation, use

Methods included from Initializer

extended

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class ROM::Changeset::Stateful

Instance Method Details

#clean?TrueClass, FalseClass

Return if there's no diff between the original and changeset data

Returns:

  • (TrueClass, FalseClass)


56
57
58
# File 'lib/rom/changeset/update.rb', line 56

def clean?
  diff.empty?
end

#commitHash

Commit update changeset if there's a diff

This returns original tuple if there's no diff

Returns:

  • (Hash)

See Also:



29
30
31
# File 'lib/rom/changeset/update.rb', line 29

def commit
  diff? ? super : original
end

#diffHash

Calculate the diff between the original and changeset data

Returns:

  • (Hash)


65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/rom/changeset/update.rb', line 65

def diff
  @diff ||=
    begin
      source = original.to_h
      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) }

      (new_tuple - (new_tuple & ori_tuple)).to_h
    end
end

#diff?TrueClass, FalseClass

Return true if there's a diff between original and changeset data

Returns:

  • (TrueClass, FalseClass)


47
48
49
# File 'lib/rom/changeset/update.rb', line 47

def diff?
  !diff.empty?
end

#originalHash

Return original tuple that this changeset may update

Returns:

  • (Hash)


38
39
40
# File 'lib/rom/changeset/update.rb', line 38

def original
  @original ||= relation.one
end