ExampleStore Ruby

From the Directed Edge Developer Base

(Redirected from ExampleStore Class)
Jump to: navigation, search
#!/usr/bin/ruby
 
require 'rubygems'
require 'activerecord'
require 'directed_edge'
 
ActiveRecord::Base.establish_connection(:adapter => 'mysql',
                                        :host => 'localhost',
                                        :username => 'examplestore',
                                        :password => 'password',
                                        :database => 'examplestore')
 
class Customer < ActiveRecord::Base
end
 
class Product < ActiveRecord::Base
end
 
class Purchase < ActiveRecord::Base
end
 
class ExampleStore
  def initialize
    @database = DirectedEdge::Database.new('examplestore', 'password')
  end
 
  def export_from_mysql
    exporter = DirectedEdge::Exporter.new('examplestore.xml')
 
    Customer.find(:all).each do |customer|
      item = DirectedEdge::Item.new(exporter.database, "customer#{customer.id}")
      item.add_tag('customer')
      purchases = Purchase.find(:all, :conditions => { :customer => customer.id })
      purchases.each { |purchase| item.link_to("product#{purchase.product}") }
      exporter.export(item)
    end
 
    Product.find(:all).each do |product|
      item = DirectedEdge::Item.new(exporter.database, "product#{product.id}")
      item.add_tag('product')
      exporter.export(item)
    end
 
    exporter.finish
  end
 
  def import_to_directededge
    @database.import('examplestore.xml')
  end
 
  def create_customer(id)
    item = DirectedEdge::Item.new(@database, "customer#{id}")
    item.add_tag('customer')
    item.save
  end
 
  def create_product(id)
    item = DirectedEdge::Item.new(@database, "product#{id}")
    item.add_tag('product')
    item.save
  end
 
  def add_purchase(customer_id, product_id)
    item = DirectedEdge::Item.new(@database, "customer#{customer_id}")
    item.link_to("product#{product_id}")
    item.save
  end
 
  def related_products(product_id)
    item = DirectedEdge::Item.new(@database, "product#{product_id}")
    item.related(['product']).map { |product| product.sub('product', '').to_i }
  end
 
  def personalized_recommendations(customer_id)
    item = DirectedEdge::Item.new(@database, "customer#{customer_id}")
    item.recommended(['product']).map { |product| product.sub('product', '').to_i }
  end
end
 
store = ExampleStore.new
 
store.export_from_mysql
store.import_to_directededge
 
store.create_customer(500)
store.create_product(2000)
store.add_purchase(500, 2000)
 
store.related_products(1).each do |product|
  puts "Related products for product 1: #{product}"
end
 
store.personalized_recommendations(1).each do |product|
  puts "Personalized recommendations for user 1: #{product}"
end