-
-
Save reinh/5126712 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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