Skip to content

Instantly share code, notes, and snippets.

@spraints
Last active August 20, 2016 22:40
Show Gist options
  • Save spraints/73d72e29489145cc445ad1321c36e7f0 to your computer and use it in GitHub Desktop.
Save spraints/73d72e29489145cc445ad1321c36e7f0 to your computer and use it in GitHub Desktop.
farmersmarket.com helpers
source "https://rubygems.org"
ruby "2.3.0"
gem "mail"
gem "nokogiri"
GEM
remote: https://rubygems.org/
specs:
mail (2.6.4)
mime-types (>= 1.16, < 4)
mime-types (3.1)
mime-types-data (~> 3.2015)
mime-types-data (3.2016.0521)
mini_portile2 (2.1.0)
nokogiri (1.6.8)
mini_portile2 (~> 2.1.0)
pkg-config (~> 1.1.7)
pkg-config (1.1.7)
PLATFORMS
ruby
DEPENDENCIES
mail
nokogiri
RUBY VERSION
ruby 2.3.0p0
BUNDLED WITH
1.12.5
#!/usr/bin/env ruby
require "mail"
require "nokogiri"
def main(raw_mail_path)
mail = Mail.read(raw_mail_path)
html = Nokogiri::HTML(mail.body.decoded)
orders = find_orders(html)
write html.css("head"), orders
end
def find_orders(html)
customer_els = html.css("strong").select { |el| el.text == "Customer:" }
order_els = customer_els.map { |el| el.ancestors("div").first }
order_els.map { |el| Order.new(el) }.sort_by(&:sort_val)
end
def write(html_head, orders)
puts "<!DOCTYPE html>", "<html>"
puts html_head
puts "<body>"
orders.each do |order|
puts order
end
puts "</body>", "</html>"
end
class Order
def initialize(order)
@order = order
end
def to_s
@order.to_s
end
def sort_val
@sort_val ||= [product, customer_number]
end
def product
@order.css("strong").find { |el| el.text == "Product:" }.next.text.strip
end
def customer_number
@order.css("span").text.gsub(/[^0-9]+/,"")
end
end
main(*ARGV)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment