Skip to content

Commit

Permalink
Don't fill in timestamp fields if they are disabled for a table
Browse files Browse the repository at this point in the history
  • Loading branch information
andrykonchin committed Oct 16, 2019
1 parent ca3e807 commit 5975039
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
15 changes: 13 additions & 2 deletions lib/dynamoid/fields.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ module Fields
class_attribute :range_key

self.attributes = {}

# Timestamp fields could be disabled later in `table` method call.
# So let's declare them here and remove them later if it will be necessary
field :created_at, :datetime if Dynamoid::Config.timestamps
field :updated_at, :datetime if Dynamoid::Config.timestamps

Expand Down Expand Up @@ -83,9 +86,13 @@ def table(options)
end

if options[:timestamps] && !Dynamoid::Config.timestamps
# Timestamp fields weren't declared in `included` hook because they
# are disabled globaly
field :created_at, :datetime
field :updated_at, :datetime
elsif options[:timestamps] == false && Dynamoid::Config.timestamps
# Timestamp fields were declared in `included` hook but they are
# disabled for a table
remove_field :created_at
remove_field :updated_at
end
Expand All @@ -107,6 +114,10 @@ def remove_field(field)
end
end

def timestamps_enabled?
options[:timestamps] || (options[:timestamps].nil? && Dynamoid::Config.timestamps)
end

private

def generated_methods
Expand Down Expand Up @@ -174,14 +185,14 @@ def read_attribute_before_type_cast(name)
#
# @since 0.2.0
def set_created_at
self.created_at ||= DateTime.now.in_time_zone(Time.zone) if Dynamoid::Config.timestamps
self.created_at ||= DateTime.now.in_time_zone(Time.zone) if self.class.timestamps_enabled?
end

# Automatically called during the save callback to set the updated_at time.
#
# @since 0.2.0
def set_updated_at
if Dynamoid::Config.timestamps && !updated_at_changed?
if self.class.timestamps_enabled? && !updated_at_changed?
self.updated_at = DateTime.now.in_time_zone(Time.zone)
end
end
Expand Down
2 changes: 1 addition & 1 deletion lib/dynamoid/persistence/import.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def call
def build_model(attributes)
attrs = attributes.symbolize_keys

if Dynamoid::Config.timestamps
if @model_class.timestamps_enabled?
time_now = DateTime.now.in_time_zone(Time.zone)
attrs[:created_at] ||= time_now
attrs[:updated_at] ||= time_now
Expand Down

0 comments on commit 5975039

Please sign in to comment.