lib/bill_hicks/inventory.rb in bill_hicks-1.3.10 vs lib/bill_hicks/inventory.rb in bill_hicks-2.0

- old
+ new

@@ -13,64 +13,45 @@ def initialize(options = {}) requires!(options, :username, :password) @options = options end - def self.all(options = {}) + def self.all(chunk_size = 15, options = {}, &block) requires!(options, :username, :password) - new(options).all + new(options).all(chunk_size, &block) end - def self.process_as_chunks(size = 15, options = {}, &block) + def self.quantities(chunk_size = 15, options = {}, &block) requires!(options, :username, :password) - new(options).process_as_chunks(size, &block) + new(options).quantities(chunk_size, &block) end - # Returns an array of hashes with the inventory item details. - def all - inventory = [] - + def all(chunk_size, &block) connect(@options) do |ftp| - ftp.chdir(BillHicks.config.top_level_dir) + begin + csv_tempfile = Tempfile.new - lines = ftp.gettextfile(INVENTORY_FILENAME, nil) + ftp.chdir(BillHicks.config.top_level_dir) + ftp.getbinaryfile(INVENTORY_FILENAME, csv_tempfile.path) - CSV.parse(lines, headers: :first_row) do |row| - inventory << { - brand_name: BillHicks::BrandConverter.convert(row.fetch('Product')), - product: row.fetch('Product'), - upc: row.fetch('UPC'), - quantity: (Integer(row.fetch('Qty Avail')) rescue 0) - } - end - end + SmarterCSV.process(csv_tempfile, { + :chunk_size => chunk_size, + :force_utf8 => true, + :convert_values_to_numeric => false, + :key_mapping => { + :qty_avail => :quantity, + :upc => :item_identifier + } + }) do |chunk| + chunk.each do |item| + item.except!(:product) + end - inventory - end - - # Streams csv and chunks it - # - # @size integer The number of items in each chunk - def process_as_chunks(size, &block) - connect(@options) do |ftp| - tempfile = Tempfile.new - - ftp.chdir(BillHicks.config.top_level_dir) - ftp.getbinaryfile(INVENTORY_FILENAME, tempfile.path) - - smart_options = { - chunk_size: size, - key_mapping: { qty_avail: :quantity }, - force_utf8: true, - convert_values_to_numeric: false - } - - SmarterCSV.process(tempfile, smart_options) do |chunk| - yield(chunk) + yield(chunk) + end + ensure + ftp.close end - - tempfile.unlink end end - end end