Skip to content

Instantly share code, notes, and snippets.

@patbenatar
Created January 12, 2013 00:16
Show Gist options
  • Save patbenatar/4515141 to your computer and use it in GitHub Desktop.
Save patbenatar/4515141 to your computer and use it in GitHub Desktop.
class Analyzer
class << self
include ActionView::Helpers::NumberHelper
end
CACHE_NAMESPACE = "analyzer"
CACHE_LIFESPAN = 10.minutes
class_attribute :items_to_analyze
def self.analyze(name, &block)
(self.items_to_analyze ||= []) << Item.new(name_prefix, name, block)
end
def initialize(collection, options={})
@collection = collection
@options = options
end
def results
@results ||= Rails.cache.fetch(cache_key, expires_in: CACHE_LIFESPAN) do
items_to_analyze.map { |i| i.call_to_hash(@collection, @options) }
end
end
def cached?
Rails.cache.exist?(cache_key)
end
private
def self.name_prefix
self.name.underscore.gsub("_analyzer", "")
end
def self.format_number(num)
number_with_delimiter(num)
end
def self.format_money(cents)
"$#{format_number(Money.new(cents))}"
end
def self.format_percentage(decimal)
"#{format_number((decimal*100).to_i)}%"
end
def collection_identifier
@collection_identifier ||=
Digest::MD5.hexdigest(coerced_collection.to_sql + @options.to_json)
end
def coerced_collection
@coerced_collection ||= if @collection.is_a?(ActiveRecord::Relation)
@collection
else
@collection.where("")
end
end
def cache_key
"#{CACHE_NAMESPACE}:#{collection_identifier}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment