Skip to content

Commit

Permalink
Use to_f for hash_cache_field to get millisecond precision for Active…
Browse files Browse the repository at this point in the history
…Support::TimeWithZone timestamps
  • Loading branch information
lgebhardt committed Jan 18, 2021
1 parent 0fea667 commit cdc5939
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
9 changes: 8 additions & 1 deletion lib/jsonapi/basic_resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1019,7 +1019,14 @@ def attribute_caching_context(_context)

# Generate a hashcode from the value to be used as part of the cache lookup
def hash_cache_field(value)
Digest::MD5.hexdigest(value.to_s)
if value.nil?
nil
elsif value.is_a?(ActiveSupport::TimeWithZone)
# for timestamps use to_f instead of computing a hash
value.to_f
else
Digest::MD5.hexdigest(value)
end
end

def _model_class
Expand Down
2 changes: 2 additions & 0 deletions test/fixtures/posts.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ post_1:
title: New post
body: A body!!!
author_id: 1001
created_at: 2020-01-01 14:15:16 UTC
updated_at: 2020-01-15 14:15:12 UTC

post_2:
id: 2
Expand Down
29 changes: 28 additions & 1 deletion test/unit/resource/resource_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ class PostWithReadonlyAttributesResource < JSONAPI::Resource

class ResourceTest < ActiveSupport::TestCase
def setup
@post = Post.first
@post = posts(:post_1)
end

def test_model_name
Expand Down Expand Up @@ -126,6 +126,33 @@ def test_resource_for_resource_does_not_exist_at_root
end
end

def test_cache_ids_are_consistent_from_run_to_run
assert_equal '2020-01-15 14:15:12 UTC', @post.updated_at.to_s

post_resource = PostResource.new(@post, {})
assert_equal [@post.id, 1579097712.0], post_resource.cache_id
end

def test_cache_ids_change_when_cache_field_is_changed
assert_equal '2020-01-15 14:15:12 UTC', @post.updated_at.to_s

post_resource = PostResource.new(@post, {})
assert_equal [@post.id, 1579097712.0], post_resource.cache_id

assert @post.touch
refute_equal [@post.id, 1579097712.0], post_resource.cache_id
end

def test_date_based_cache_ids_change_with_milliseconds_if_hash_cache_field_is_time_stamp
assert_equal '2020-01-15 14:15:12 UTC', @post.updated_at.to_s

post_resource = PostResource.new(@post, {})
assert_equal [@post.id, 1579097712.0], post_resource.cache_id

@post.updated_at = @post.updated_at + 0.222
refute_equal [@post.id, 1579097712.0], post_resource.cache_id
end

def test_resource_for_with_underscored_namespaced_paths
assert_equal(JSONAPI::Resource.resource_klass_for('my_module/related'), MyModule::RelatedResource)
assert_equal(PostResource.resource_klass_for('my_module/related'), MyModule::RelatedResource)
Expand Down

0 comments on commit cdc5939

Please sign in to comment.