Skip to content

Instantly share code, notes, and snippets.

@MichaelXavier
Created June 29, 2010 01:22
Show Gist options
  • Save MichaelXavier/456651 to your computer and use it in GitHub Desktop.
Save MichaelXavier/456651 to your computer and use it in GitHub Desktop.
class Product
# .. junk
has_many :prices
# Returns a hash with the min, max and average for the range defined under
# the Prices aggregatable scope
def min_max_avg
map = "function() { emit(this.product_id, {amount: this.amount, qty: this.qty});}"
reduce = <<-JS
function(price_id, vals) {
var min = vals[0].amount;
var max = min;
var E_w = vals[0].qty;
var E_v = max;
for (var i = 1; i < vals.length; i++) {
vals[i].amount < min && (min = vals[i].amount);
vals[i].amount > max && (max = vals[i].amount);
E_w += vals[i].qty;
E_v += vals[i].amount;
}
return {min: min, max: max, avg: (E_v/E_w)};
}
JS
# Aggregatable just puts in the condition that recorded_on is at most 5 days in the past
prices.aggregatable.collection.map_reduce(map,reduce, {:query => {:product_id => id}}).find.to_a#MXDEBUG: whats this return look like
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment