-
-
Notifications
You must be signed in to change notification settings - Fork 197
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refactor .inc and move code to a separate class
- Loading branch information
1 parent
7e2587e
commit ad2e636
Showing
2 changed files
with
66 additions
and
34 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
# frozen_string_literal: true | ||
|
||
module Dynamoid | ||
module Persistence | ||
# @private | ||
class Inc | ||
def self.call(model_class, hash_key, range_key = nil, counters) | ||
new(model_class, hash_key, range_key, counters).call | ||
end | ||
|
||
def initialize(model_class, hash_key, range_key = nil, counters) | ||
@model_class = model_class | ||
@hash_key = hash_key | ||
@range_key = range_key | ||
@counters = counters | ||
end | ||
|
||
def call | ||
touch = @counters.delete(:touch) | ||
|
||
Dynamoid.adapter.update_item(@model_class.table_name, @hash_key, update_item_options) do |t| | ||
@counters.each do |name, value| | ||
t.add(name => cast_and_dump_attribute_value(name, value)) | ||
end | ||
|
||
if touch | ||
value = DateTime.now.in_time_zone(Time.zone) | ||
|
||
timestamp_attributes_to_touch(touch).each do |name| | ||
t.set(name => cast_and_dump_attribute_value(name, value)) | ||
end | ||
end | ||
end | ||
end | ||
|
||
private | ||
|
||
def update_item_options | ||
if @model_class.range_key | ||
range_key_options = @model_class.attributes[@model_class.range_key] | ||
value_casted = TypeCasting.cast_field(@range_key, range_key_options) | ||
value_dumped = Dumping.dump_field(value_casted, range_key_options) | ||
{ range_key: value_dumped } | ||
else | ||
{} | ||
end | ||
end | ||
|
||
def cast_and_dump_attribute_value(name, value) | ||
value_casted = TypeCasting.cast_field(value, @model_class.attributes[name]) | ||
Dumping.dump_field(value_casted, @model_class.attributes[name]) | ||
end | ||
|
||
def timestamp_attributes_to_touch(touch) | ||
return [] unless touch | ||
|
||
names = [] | ||
names << :updated_at if @model_class.timestamps_enabled? | ||
names += Array.wrap(touch) if touch != true | ||
names | ||
end | ||
end | ||
end | ||
end |