lib/gov_kit/resource.rb in govkit-0.3.2 vs lib/gov_kit/resource.rb in govkit-0.4.0
- old
+ new
@@ -7,39 +7,56 @@
attr_reader :raw_response
def initialize(attributes = {})
@attributes = {}
@raw_response = attributes
+
unload(attributes)
end
class << self
- def instantiate_record(record)
- raise ResourceNotFound, "Resource not found" unless !record.blank?
- new(record)
- end
+ def parse(response)
+ # This method handles the basic responses we might get back from
+ # Net::HTTP. But if a service returns something other than a 404 when an object is not found,
+ # you'll need to handle that in the subclass.
+
+ raise ResourceNotFound, "Resource not found" unless !response.blank?
- def instantiate_collection(collection)
- collection.collect! { |record| instantiate_record(record) }
+ if response.class == HTTParty::Response
+ case response.response
+ when Net::HTTPNotFound
+ raise ResourceNotFound, "404 Not Found"
+ when Net::HTTPUnauthorized
+ raise NotAuthorized, "401 Not Authorized; have you set up your API key?"
+ end
+ end
+
+ instantiate(response)
end
- def parse(json)
- instantiate(json)
- end
-
def instantiate(record)
case record
when Array
instantiate_collection(record)
- when Hash
+ else
instantiate_record(record)
end
end
+
+ def instantiate_record(record)
+ new(record)
+ end
+
+ def instantiate_collection(collection)
+ collection.collect! { |record| instantiate_record(record) }
+ end
+
end
def unload(attributes)
raise ArgumentError, "expected an attributes Hash, got #{attributes.inspect}" unless attributes.is_a?(Hash)
+
attributes.each do |key, value|
@attributes[key.to_s] =
case value
when Array
resource = resource_for_collection(key)
@@ -72,10 +89,10 @@
raise NameError, "Namespace for #{namespace} not found"
end
end
def find_or_create_resource_for(name)
- resource_name = name.to_s.gsub(/^[_+]/,'').gsub(/^(\d)/, "n#{$1}").gsub(/\s/, '').camelize
+ resource_name = name.to_s.gsub(/^(\d)/, "n#{$1}").gsub(/\s/, '').camelize
if self.class.parents.size > 1
find_resource_in_modules(resource_name, self.class.parents)
else
self.class.const_get(resource_name)
end