Skip to content

Commit

Permalink
Add cache_key and cache_version to shim
Browse files Browse the repository at this point in the history
  • Loading branch information
gburgett committed Aug 8, 2019
1 parent 7a62b78 commit 699e63a
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 0 deletions.
20 changes: 20 additions & 0 deletions wcc-contentful/lib/wcc/contentful/active_record_shim.rb
Expand Up @@ -7,6 +7,26 @@ def attributes
@attributes ||= to_h['fields'].tap { |fields| fields['id'] = id }
end

def cache_key
key = "#{self.class.model_name}/#{id}"
key += "-#{cache_version}" unless ActiveRecord::Base.try(:cache_versioning) == true
key
end

def cache_key_with_version
"#{self.class.model_name}/#{id}-#{cache_version}"
end

def cache_version
sys.revision.to_s
end

included do
unless defined?(ActiveRecord)
raise NotImplementedError, 'WCC::Contentful::ActiveRecordShim requires ActiveRecord to be loaded'
end
end

class_methods do
def model_name
WCC::Contentful::Helpers.constant_from_content_type(content_type)
Expand Down
72 changes: 72 additions & 0 deletions wcc-contentful/spec/wcc/contentful/active_record_shim_spec.rb
@@ -1,10 +1,38 @@
# frozen_string_literal: true

require 'spec_helper'
require 'active_record'

class ShimTest
include WCC::Contentful::ActiveRecordShim

def initialize(raw)
@raw = raw.freeze

created_at = raw.dig('sys', 'createdAt')
created_at = Time.parse(created_at) if created_at.present?
updated_at = raw.dig('sys', 'updatedAt')
updated_at = Time.parse(updated_at) if updated_at.present?
@sys = WCC::Contentful::Sys.new(
raw.dig('sys', 'id'),
raw.dig('sys', 'type'),
raw.dig('sys', 'locale') || 'en-US',
raw.dig('sys', 'space', 'sys', 'id'),
created_at,
updated_at,
raw.dig('sys', 'revision'),
OpenStruct.new.freeze
)
end

attr_reader :sys
attr_reader :raw
delegate :id, to: :sys
delegate :created_at, to: :sys
delegate :updated_at, to: :sys
delegate :revision, to: :sys
delegate :space, to: :sys

def self.content_type
'shim-test'
end
Expand Down Expand Up @@ -82,4 +110,48 @@ class ConstGetTest < ShimTest::ConstGetTest
expect(got).to eq(ConstGetTest)
end
end

describe '#cache_key' do
let(:raw) {
{
'sys' => {
'id' => 'ax1234',
'type' => 'Entry',
'createdAt' => '2019-05-10T18:59:25.828Z',
'updatedAt' => '2019-05-10T18:59:25.828Z',
'revision' => 1
},
'fields' => {}
}
}
let(:subject) { ShimTest.new(raw) }

context 'Rails 5.2' do
before do
allow(ActiveRecord::Base).to receive(:try)
.with(:cache_versioning)
.and_return(true)
end

it { expect(subject.cache_key).to eq('ShimTest/ax1234') }

it '#cache_version' do
expect(subject.cache_version).to eq('1')
end

it '#cache_key_with_version' do
expect(subject.cache_key_with_version).to eq('ShimTest/ax1234-1')
end
end

context 'Rails 5.1 and before' do
before do
allow(ActiveRecord::Base).to receive(:try)
.with(:cache_versioning)
.and_return(nil)
end

it { expect(subject.cache_key).to eq('ShimTest/ax1234-1') }
end
end
end

0 comments on commit 699e63a

Please sign in to comment.