1
0
Fork 0
forked from OpenNeo/impress
impress/app/models/neopets_user.rb

79 lines
2 KiB
Ruby
Raw Normal View History

2011-08-03 08:35:06 -07:00
require 'open-uri'
class NeopetsUser
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :username
2013-08-17 09:07:04 -07:00
attr_reader :hangers, :list_id
2011-08-03 08:35:06 -07:00
def initialize(app_user)
@app_user = app_user
end
2013-08-17 09:07:04 -07:00
def list_id=(list_id)
# TODO: DRY up with ClosetPage
@list_id = list_id
if list_id == 'true'
@closet_list = nil
@hangers_owned = true
elsif list_id == 'false'
@closet_list = nil
@hangers_owned = false
elsif list_id.present?
@closet_list = @app_user.closet_lists.find(list_id)
@hangers_owned = @closet_list.hangers_owned?
end
end
2011-08-03 08:35:06 -07:00
def load!
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
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)
item_quantities = {}
items.each do |i|
item_quantities[i] ||= 0
item_quantities[i] += 1
end
2011-08-03 08:35:06 -07:00
2013-08-17 09:07:04 -07:00
# TODO: DRY up with ClosetPage
# We don't want to insert duplicate hangers of what a user owns if they
# already have it in another list (e.g. imports to Items You Own *after*
# curating their Up For Trade list), so we check for the hanger's presence
# in *all* items the user owns or wants (whichever is appropriate for this
# request).
hangers_scope = @app_user.closet_hangers.where(owned: @hangers_owned)
existing_hanger_item_ids = hangers_scope.select(:item_id).
where(item_id: item_ids).map(&:item_id)
2011-08-03 08:35:06 -07:00
@hangers = []
item_quantities.each do |item, quantity|
2011-08-03 08:35:06 -07:00
next if existing_hanger_item_ids.include?(item.id)
2013-08-17 09:07:04 -07:00
hanger = hangers_scope.build
2011-08-03 08:35:06 -07:00
hanger.item = item
hanger.quantity = quantity
2013-08-17 09:07:04 -07:00
hanger.list = @closet_list
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
class NotFound < RuntimeError; end
2011-08-03 08:35:06 -07:00
end