Skip to content

Instantly share code, notes, and snippets.

@rthbound
Created January 15, 2012 20:02
Show Gist options
  • Select an option

  • Save rthbound/1617005 to your computer and use it in GitHub Desktop.

Select an option

Save rthbound/1617005 to your computer and use it in GitHub Desktop.
hot_parts
def hot_parts
# initialize some empties
hps = []
hp = false
# get 6 random parts
while(hps.length < 6 )
# Set flag variable to ensure entry into inner loop first time around
first = true
# Validate uniqueness and non nillishness
while( hps.include?(hp) || !hp.present? || first )
if order = Order.within_days(15).rand
# Grab a random part if there are any to choose from
hp = order.order_products.last.part_number if order.order_products.present?
first = false
end
end
# Assume it has no photos
has_photos = false
# Don't care if it has photos if it's not in stock
if hp.quantity > 0
# If it has an album and some photos in that album, it might have photos
has_photos = !hp.album.photos.empty? if hp.album.present?
# It definitely has photos if the above was true and the first photo has an image_file!
has_photos = true if has_photos && hp.album.photos.first.image_file.present?
end
# Validate everything we show in the view:
# is_valid = ![hp.price.present?, hp.manufacturer.present?, hp.name.present?, hp.number.present?, hp.to_param.present?].include?(false)
# Shove it in the array if it's stocked and has an image
hps << hp if has_photos# && is_valid
#hps.uniq! #uniquness guaranteed by inner while loop condition
#hps.compact!
end
# randomize, reject all non-uniques
hps.present? ? hps.sort!{rand} : []
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment