Skip to content

Instantly share code, notes, and snippets.

@reinh
Forked from justinko/daily_planet_export.txt
Last active December 14, 2015 18:08
Show Gist options
  • Save reinh/5126712 to your computer and use it in GitHub Desktop.
Save reinh/5126712 to your computer and use it in GitHub Desktop.
Merchant Date Ends Deal Price Value
Burger King 10/2/2011 10/4/2011 Your way 25 50
McDonalds 10/5/2011 Not really food 22 44
Arbys 10/8/2011 10/10/2011 More burgers 7 14
namespace :publisher do
desc "Import a publisher's data"
task :import, [:file_path, :publisher_name] => [:environment] do |t, args|
args.with_defaults(
file_path: Rails.root.join('script/data/daily_planet_export.txt'),
publisher_name: 'The Daily Planet'
)
file = File.new(args[:file_path])
publisher = Publisher.find_or_create_by_name(args[:publisher_name])
PublisherImporter.new(publisher, file).import
end
end
class PublisherImporter
def initialize(publisher, file)
@publisher = publisher
@file = file
end
def import
each_row do |row|
RowScanner.new(row).create_deal(@publisher)
end
end
private
def each_row
@file.drop(1).each {|line| yield line.chomp }
end
class RowScanner
def initialize(str)
@string_scanner = StringScanner.new(str)
end
def create_deal(publisher)
advertiser = publisher.advertisers.find_or_create_by_name(scan_words)
advertiser.deals.create to_hash
end
private
def scan_words
@string_scanner.scan(/\D+/)
end
def scan_date
@string_scanner.scan(/\d{1,2}\/\d{1,2}\/\d{2,4}\s*/)
end
def scan_digits
@string_scanner.scan(/\d+\s*/)
end
def to_hash
{
start_at: scan_date,
end_at: scan_date,
description: scan_words,
price: scan_digits,
value: scan_digits
}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment