require 'rubygems' require 'csv' require 'mechanize' def get_price(price_string) price_string.gsub(',','').to_i end arr_of_arrs = CSV.read(File.join(File.dirname(__FILE__), "assets/pricelist.csv")) header = arr_of_arrs.shift reference_index = header.index("Reference") retail_price_index = header.index("Retail") wholesale_price_index = header.index("Wholesale") a = Mechanize.new # for each reference in the pricelist, update the price in the catalog arr_of_arrs.each do |array| reference = array[reference_index] retail_price = get_price(array[retail_price_index]) wholesale_price = get_price(array[wholesale_price_index]) a.get('http://localhost:3000/catalog_items?show=all') do |catalog_items_index| edit_link = catalog_items_index.parser.xpath("//span[text()='#{reference}']/../p/a[text()='Edit']") if edit_link.size > 0 puts "Updating prices for reference #{reference}." # go to the edit page for that reference edit_link = edit_link.first edit_catalog_item_page = a.click(edit_link) edit_catalog_item_page.form_with(:method => 'POST') do |f| f.field_with(:id => 'catalog_item_retail_price').value = retail_price f.field_with(:id => 'catalog_item_wholesale_price').value = wholesale_price end.submit else puts "Couldn't find reference #{reference} in system." end end end