Skip to content

Instantly share code, notes, and snippets.

@bigfleet
Created September 16, 2009 14:16
Show Gist options
  • Save bigfleet/188064 to your computer and use it in GitHub Desktop.
Save bigfleet/188064 to your computer and use it in GitHub Desktop.
require 'mongo'
require 'mongo_record'
require 'memcached'
MongoRecord::Base.connection =
Mongo::Connection.new("75.101.206.153").db('trader_network_trois')
$cache = Memcached.new("localhost:11211")
class ItemOfInterest < MongoRecord::Base
collection_name :items_of_interest
fields :type, :id, :json, :interested
end
class Interest < MongoRecord::Subobject
fields :member_id, :cause, :cause_type, :cause_id
end
class MongoTest
def self.cache_key(type, id)
[type, id].join(":")
end
...
end
trade = Trade.find(5187411)
items = trade.distributions
RAILS_DEFAULT_LOGGER.info("Distributing item to #{items.size} members")
items.each_with_index do |afi, iteration|
key_hash = {:type => afi.real_item_type, :id => afi.item_of_interest_id}
ioi = ItemOfInterest.find(:first, :conditions => key_hash)
RAILS_DEFAULT_LOGGER.info("Iteration #{iteration}: Interested size (at load): #{ioi.interested.size}") if ioi
unless ioi
ioi = ItemOfInterest.new(key_hash)
begin
ioi.json = $cache.get(MongoTest.cache_key(afi.item_of_interest_type, afi.item_of_interest_id))
rescue Memcached::NotFound
ioi.json = afi.item_of_interest.to_json
$cache.set(MongoTest.cache_key(afi.item_of_interest_type, afi.item_of_interest_id),ioi.json)
end
ioi.interested = []
end
begin
cause_json = $cache.get(MongoTest.cache_key(afi.cause_type, afi.cause_id))
rescue Memcached::NotFound
cause_json = afi.cause.to_json
$cache.set(MongoTest.cache_key(afi.cause_type, afi.cause_id),cause_json)
end
RAILS_DEFAULT_LOGGER.info("Iteration #{iteration}: Interested size (before append): #{ioi.interested.size}")
ioi.interested << Interest.new(:member_id => afi.member_id, :cause => cause_json,
:cause_type => afi.real_cause_type, :cause_id => afi.cause_id)
RAILS_DEFAULT_LOGGER.info("Iteration #{iteration}: Interested size (after append): #{ioi.interested.size}")
ioi.save
RAILS_DEFAULT_LOGGER.info("Iteration #{iteration}: Interested size (after save): #{ioi.interested.size}")
end
Iteration 0: Interested size (before append): 0
Iteration 0: Interested size (after append): 1
Iteration 0: Interested size (after save): 1
Iteration 1: Interested size (at load): 1
Iteration 1: Interested size (before append): 1
Iteration 1: Interested size (after append): 2
Iteration 1: Interested size (after save): 2
Iteration 2: Interested size (at load): 1
Iteration 2: Interested size (before append): 1
Iteration 2: Interested size (after append): 2
Iteration 2: Interested size (after save): 2
Iteration 3: Interested size (at load): 1
Iteration 3: Interested size (before append): 1
Iteration 3: Interested size (after append): 2
Iteration 3: Interested size (after save): 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment