lib/renderful/client.rb in renderful-0.2.0 vs lib/renderful/client.rb in renderful-0.3.0
- old
+ new
@@ -1,35 +1,46 @@
# frozen_string_literal: true
module Renderful
class Client
- attr_reader :contentful, :renderers, :cache
+ attr_reader :provider, :components, :cache
- def initialize(contentful:, renderers:, cache: nil)
- @contentful = contentful
- @renderers = renderers
+ def initialize(provider:, components:, cache: Cache::Null.new)
+ @provider = provider
+ @components = components
@cache = cache
end
- def render(entry)
- renderer = renderers[entry.content_type.id]
- fail(NoRendererError, entry) unless renderer
+ def render(entry_id, options = {})
+ cache.fetch(ContentEntry.build_cache_key(provider, id: entry_id)) do
+ content_entry = provider.find_entry(entry_id)
+ component = component_for_entry(content_entry)
- return cache.read(cache_key_for(entry)) if cache&.exist?(cache_key_for(entry))
-
- renderer.new(entry, client: self).render.tap do |output|
- cache&.write(cache_key_for(entry), output)
+ if component.respond_to?(:render_in)
+ component.render_in(options.fetch(:view_context))
+ else
+ component.render
+ end
end
end
- def cache_key_for(entry)
- if entry.respond_to?(:content_type)
- cache_key_for(
- content_type_id: entry.content_type.id,
- entry_id: entry.id,
- )
- else
- "contentful/#{entry.fetch(:content_type_id)}/#{entry.fetch(:entry_id)}"
+ def invalidate_cache_from_webhook(body)
+ result = provider.cache_keys_to_invalidate(body)
+
+ cache.delete(*result[:keys])
+
+ result[:patterns].each do |pattern|
+ cache.delete_matched(pattern)
end
+ end
+
+ private
+
+ def component_klass_for_entry(content_entry)
+ components[content_entry.content_type] || fail(Error::NoComponentError, content_entry)
+ end
+
+ def component_for_entry(content_entry)
+ component_klass_for_entry(content_entry).new(entry: content_entry, client: self)
end
end
end