From ff629b94193b1e9d4d3e512e10da14b23ba4b491 Mon Sep 17 00:00:00 2001 From: Matchu Date: Fri, 8 Oct 2010 10:53:28 -0400 Subject: [PATCH] pet type now loads image hash on save --- app/models/pet.rb | 1 + app/models/pet_type.rb | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/app/models/pet.rb b/app/models/pet.rb index 5ea031cb..6649c25c 100644 --- a/app/models/pet.rb +++ b/app/models/pet.rb @@ -25,6 +25,7 @@ class Pet < ActiveRecord::Base pet_data.color_id.to_i ) self.pet_type.body_id = pet_data.body_id + self.pet_type.origin_pet = self @pet_state = self.pet_type.add_pet_state_from_biology! pet_data.biology_by_zone @items = Item.collection_from_pet_type_and_registries(self.pet_type, contents.object_info_registry, contents.object_asset_registry) diff --git a/app/models/pet_type.rb b/app/models/pet_type.rb index 88e00b5f..27e31898 100644 --- a/app/models/pet_type.rb +++ b/app/models/pet_type.rb @@ -1,6 +1,13 @@ +require 'open-uri' + class PetType < ActiveRecord::Base + IMAGE_CPN_FORMAT = 'http://pets.neopets.com/cpn/%s/1/1.png'; + IMAGE_CP_LOCATION_REGEX = %r{^/cp/(.+?)/1/1\.png$}; + has_many :pet_states + attr_writer :origin_pet + BasicHashes = YAML::load_file(Rails.root.join('config', 'basic_type_hashes.yml')) StandardBodyIds = PetType.select(arel_table[:body_id]). @@ -60,4 +67,27 @@ class PetType < ActiveRecord::Base self.pet_states << pet_state pet_state end + + def before_save + if @origin_pet + cpn_uri = URI.parse sprintf(IMAGE_CPN_FORMAT, @origin_pet.name); + res = Net::HTTP.get_response(cpn_uri) + unless res.is_a? Net::HTTPFound + begin + res.error! + rescue Exception => e + raise "Error loading CPN image at #{cpn_uri}: #{e.message}" + else + raise "Error loading CPN image at #{cpn_uri}. Response: #{res.inspect}" + end + end + new_url = res['location'] + match = new_url.match(IMAGE_CP_LOCATION_REGEX) + if match + self.image_hash = match[1] + else + raise "CPN image pointed to #{new_url}, which does not match CP image format" + end + end + end end