Skip to content

Instantly share code, notes, and snippets.

@justinko
Created March 10, 2013 01:36
Show Gist options
  • Save justinko/5126687 to your computer and use it in GitHub Desktop.
Save justinko/5126687 to your computer and use it in GitHub Desktop.
Example of Ruby's StringScanner class.
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|
row_scanner = RowScanner.new(row)
advertiser = @publisher.advertisers.find_or_create_by_name(row_scanner.scan_words)
advertiser.deals.create(
start_at: row_scanner.scan_date,
end_at: row_scanner.scan_date,
description: row_scanner.scan_words,
price: row_scanner.scan_digits,
value: row_scanner.scan_digits
)
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 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
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment