More cool stuff with ruby’s tap method

I had to write up a quick data processor at work today and I wanted a decent output at the end of execution. The ruby tap method came in handy here.

class AssetDeliveryPopulater
 
  def self.populate
    results_text = []
    asset_secrets_count, asset_delivery_count, asset_not_found_count, asset_delivery_creation_errors = 0,0,0,0
 
    Email.all.tap{|emails| results_text << "#{emails.length} emails parsed." }.each do |e|
      next unless e.body
 
      asset_secrets = extract_asset_secrets_from_text(e.body)
      next unless asset_secrets
 
      asset_secrets.tap{|as| asset_secrets_count += as.length}.each do |asset_secret|
        if a = Asset.find_by_secret(asset_secret)
          if ad = AssetDelivery.create(
              :asset => a,
              :campaign => e.campaign,
              :client => e.client,
              :created_at => e.created_at
            )
            asset_delivery_count += 1
            puts "Recorded an asset delivery: #{ad.inspect}"
          else
            asset_delivery_creation_errors += 1
            puts "Could not record the delivery: #{ad.errors.inspect}"
          end
        else
          asset_not_found_count += 1
          puts "Could not find asset with secret #{asset_secret}"
        end
      end
    end
 
    results_text << "#{asset_secrets_count} asset secrets found."
    results_text << "#{asset_delivery_count} asset deliveries recorded."
    results_text << "#{asset_not_found_count} assets not found."
    results_text << "#{asset_delivery_creation_errors} asset delivery records not created due to errors."
    puts results_text.join("\n")
  end
 
  # Given some text, extract secret asset hashes and return an array
  def self.extract_asset_secrets_from_text(text)
    text.scan(/http:\/\/[^'\/]+\/products\/([^'\/]+)/).first
  end
end
No TweetBacks yet. (Be the first to Tweet this post)
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • MySpace
  • Slashdot
  • StumbleUpon
  • Technorati
  • TwitThis

If you enjoyed this post, make sure you subscribe to my RSS feed!

This entry was posted in Software and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">