Skip to content

Instantly share code, notes, and snippets.

@bloudermilk
Forked from patbenatar/analyzer.rb
Last active December 11, 2015 00:18
Show Gist options
  • Save bloudermilk/4515175 to your computer and use it in GitHub Desktop.
Save bloudermilk/4515175 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 self.inherited(klass)
klass.items_to_analyze = []
end
def self.recursive_items_to_analyze
items = items_to_analyze
items += super if superclass.respond_to?(:recursive_items_to_analyze)
items
end
def initialize(collection, options={})
@collection = collection
@options = options
end
def results
@results ||= Rails.cache.fetch(cache_key, expires_in: CACHE_LIFESPAN) do
self.class.recursive_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