2011-08-03 08:35:06 -07:00
|
|
|
require 'open-uri'
|
|
|
|
|
|
|
|
class NeopetsUser
|
|
|
|
include ActiveModel::Conversion
|
|
|
|
extend ActiveModel::Naming
|
|
|
|
|
|
|
|
attr_accessor :username
|
|
|
|
attr_reader :hangers
|
|
|
|
|
|
|
|
def initialize(app_user)
|
|
|
|
@app_user = app_user
|
|
|
|
end
|
|
|
|
|
|
|
|
def load!
|
2012-05-21 09:48:19 -07:00
|
|
|
user = Neopets::User.new(@username)
|
|
|
|
|
|
|
|
begin
|
|
|
|
pets = user.pets
|
|
|
|
rescue Neopets::User::Error => e
|
|
|
|
raise NotFound, e.message
|
2011-08-03 08:35:06 -07:00
|
|
|
end
|
|
|
|
|
2012-05-21 09:48:19 -07:00
|
|
|
pets = pets.map { |pet| Pet.find_or_initialize_by_name(pet.name) }
|
2011-08-03 08:35:06 -07:00
|
|
|
items = pets.each(&:load!).map(&:items).flatten
|
|
|
|
item_ids = items.map(&:id)
|
|
|
|
existing_hanger_item_ids = @app_user.closet_hangers.select(:item_id).where(:item_id => item_ids).map(&:item_id)
|
2012-10-01 11:22:17 -07:00
|
|
|
item_quantities = {}
|
|
|
|
items.each do |i|
|
|
|
|
item_quantities[i] ||= 0
|
|
|
|
item_quantities[i] += 1
|
|
|
|
end
|
2011-08-03 08:35:06 -07:00
|
|
|
|
|
|
|
@hangers = []
|
2012-10-01 11:22:17 -07:00
|
|
|
item_quantities.each do |item, quantity|
|
2011-08-03 08:35:06 -07:00
|
|
|
next if existing_hanger_item_ids.include?(item.id)
|
|
|
|
hanger = @app_user.closet_hangers.build
|
|
|
|
hanger.item = item
|
2012-10-01 11:22:17 -07:00
|
|
|
hanger.quantity = quantity
|
2011-08-03 08:35:06 -07:00
|
|
|
@hangers << hanger
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def save_hangers!
|
|
|
|
ClosetHanger.transaction { @hangers.each(&:save!) }
|
|
|
|
end
|
|
|
|
|
|
|
|
def persisted?
|
|
|
|
false
|
|
|
|
end
|
2012-05-21 09:48:19 -07:00
|
|
|
|
|
|
|
class NotFound < RuntimeError; end
|
2011-08-03 08:35:06 -07:00
|
|
|
end
|
|
|
|
|