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)
If you enjoyed this post, make sure you subscribe to my RSS feed!










2 Comments
This is dumb. You’re already processing a block on your asset_secrets object. You’re just adding clutter by using tap here. You can accomplish the exact same thing by putting
asset_secrets_count += as.lengthin the first line of your block. Easier to read, less code. This isn’t what tap was made for.You’re right Mr. McJohnson. I’m not sure why I did this and then decided to write a post, it was probably impulsive as I was just screwing around with tap. Thanks for calling me out