lib/dynamoid/document.rb in dynamoid-2.0.0 vs lib/dynamoid/document.rb in dynamoid-2.1.0
- old
+ new
@@ -117,9 +117,80 @@
when Hash then where(id_or_conditions).first.present?
else !! find_by_id(id_or_conditions)
end
end
+ def update(hash_key, range_key_value=nil, attrs)
+ if range_key.present?
+ range_key_value = dump_field(range_key_value, attributes[self.range_key])
+ else
+ range_key_value = nil
+ end
+
+ model = find(hash_key, range_key: range_key_value, consistent_read: true)
+ model.update_attributes(attrs)
+ model
+ end
+
+ def update_fields(hash_key_value, range_key_value=nil, attrs={}, conditions={})
+ optional_params = [range_key_value, attrs, conditions].compact
+ if optional_params.first.is_a?(Hash)
+ range_key_value = nil
+ attrs, conditions = optional_params[0 .. 1]
+ else
+ range_key_value = optional_params.first
+ attrs, conditions = optional_params[1 .. 2]
+ end
+
+ options = if range_key
+ { range_key: dump_field(range_key_value, attributes[range_key]) }
+ else
+ {}
+ end
+
+ (conditions[:if_exists] ||= {})[hash_key] = hash_key_value
+ options[:conditions] = conditions
+
+ begin
+ new_attrs = Dynamoid.adapter.update_item(table_name, hash_key_value, options) do |t|
+ attrs.symbolize_keys.each do |k, v|
+ t.set k => dump_field(v, attributes[k])
+ end
+ end
+ new(new_attrs)
+ rescue Dynamoid::Errors::ConditionalCheckFailedException
+ end
+ end
+
+ def upsert(hash_key_value, range_key_value=nil, attrs={}, conditions={})
+ optional_params = [range_key_value, attrs, conditions].compact
+ if optional_params.first.is_a?(Hash)
+ range_key_value = nil
+ attrs, conditions = optional_params[0 .. 1]
+ else
+ range_key_value = optional_params.first
+ attrs, conditions = optional_params[1 .. 2]
+ end
+
+ options = if range_key
+ { range_key: dump_field(range_key_value, attributes[range_key]) }
+ else
+ {}
+ end
+
+ options[:conditions] = conditions
+
+ begin
+ new_attrs = Dynamoid.adapter.update_item(table_name, hash_key_value, options) do |t|
+ attrs.symbolize_keys.each do |k, v|
+ t.set k => dump_field(v, attributes[k])
+ end
+ end
+ new(new_attrs)
+ rescue Dynamoid::Errors::ConditionalCheckFailedException
+ end
+ end
+
def deep_subclasses
subclasses + subclasses.map(&:deep_subclasses).flatten
end
end