Extract integrity checking to lib class

This commit is contained in:
Rohan Mitchell
2016-03-02 11:01:41 +11:00
parent f394cf559c
commit 2abee3fcdd
3 changed files with 50 additions and 24 deletions

View File

@@ -1,31 +1,17 @@
require 'open_food_network/products_renderer'
require 'open_food_network/products_cache_integrity_checker'
ProductsCacheIntegrityCheckerJob = Struct.new(:distributor_id, :order_cycle_id) do
def perform
if diff.any?
Bugsnag.notify RuntimeError.new("Products JSON differs from cached version for distributor: #{distributor_id}, order cycle: #{order_cycle_id}"), diff: diff.to_s(:text)
unless checker.ok?
Bugsnag.notify RuntimeError.new("Products JSON differs from cached version for distributor: #{distributor_id}, order cycle: #{order_cycle_id}"), diff: checker.diff.to_s(:text)
end
end
private
def diff
@diff ||= Diffy::Diff.new pretty(cached_json), pretty(rendered_json)
end
def pretty(json)
JSON.pretty_generate JSON.parse json
end
def cached_json
Rails.cache.read("products-json-#{distributor_id}-#{order_cycle_id}") || {}.to_json
end
def rendered_json
OpenFoodNetwork::ProductsRenderer.new(distributor, order_cycle).products_json
rescue OpenFoodNetwork::ProductsRenderer::NoProducts
nil
def checker
OpenFoodNetwork::ProductsCacheIntegrityChecker.new(distributor, order_cycle)
end
def distributor

View File

@@ -0,0 +1,44 @@
require 'open_food_network/products_renderer'
module OpenFoodNetwork
class ProductsCacheIntegrityChecker
def initialize(distributor, order_cycle)
@distributor = distributor
@order_cycle = order_cycle
end
def ok?
diff.none?
end
def diff
@diff ||= Diffy::Diff.new pretty(cached_json), pretty(rendered_json)
end
def self.active_exchanges
Exchange.
outgoing.
joins(:order_cycle).
merge(OrderCycle.dated).
merge(OrderCycle.not_closed)
end
private
def cached_json
Rails.cache.read("products-json-#{@distributor.id}-#{@order_cycle.id}") || {}.to_json
end
def rendered_json
OpenFoodNetwork::ProductsRenderer.new(@distributor, @order_cycle).products_json
rescue OpenFoodNetwork::ProductsRenderer::NoProducts
nil
end
def pretty(json)
JSON.pretty_generate JSON.parse json
end
end
end

View File

@@ -19,11 +19,7 @@ namespace :openfoodnetwork do
private
def active_exchanges
Exchange.
outgoing.
joins(:order_cycle).
merge(OrderCycle.dated).
merge(OrderCycle.not_closed)
ProductsCacheIntegrityChecker.active_exchanges
end
end
end