lib/gov_kit/resource.rb in govkit-0.1.0 vs lib/gov_kit/resource.rb in govkit-0.2.0
- old
+ new
@@ -1,31 +1,6 @@
module GovKit
- class GovKitError < StandardError
- attr_reader :response
-
- def initialize(response, message = nil)
- @response = response
- @message = message
- end
-
- def to_s
- "Failed with #{response.code} #{response.message if response.respond_to?(:message)}"
- end
- end
-
- class NotauthorizedError < GovKitError;
- end
-
- class InvalidRequestError < GovKitError;
- end
-
- class NotFoundError < GovKitError;
- end
-
- class NameError < GovKitError;
- end
-
class Resource
include HTTParty
format :json
attr_accessor :attributes
@@ -35,20 +10,30 @@
unload(attributes)
end
class << self
def instantiate_record(record)
+ raise ResourceNotFound, "Resource not found" unless !record.blank?
new(record)
end
def instantiate_collection(collection)
collection.collect! { |record| instantiate_record(record) }
end
def parse(json)
- instantiate_record(json)
+ instantiate(json)
end
+
+ def instantiate(record)
+ case record
+ when Array
+ instantiate_collection(record)
+ when Hash
+ instantiate_record(record)
+ end
+ end
end
def unload(attributes)
raise ArgumentError, "expected an attributes Hash, got #{attributes.inspect}" unless attributes.is_a?(Hash)
attributes.each do |key, value|
@@ -76,27 +61,22 @@
private
def resource_for_collection(name)
find_or_create_resource_for(name.to_s.singularize)
end
- def find_resource_in_modules(resource_name, module_names)
- receiver = Object
- namespaces = module_names[0, module_names.size-1].map do |module_name|
- receiver = receiver.const_get(module_name)
- end
- if namespace = namespaces.reverse.detect { |ns| ns.const_defined?(resource_name) }
+ def find_resource_in_modules(resource_name, ancestors)
+ if namespace = ancestors.detect { |a| a.constants.include?(resource_name.to_sym) }
return namespace.const_get(resource_name)
else
raise NameError, "Namespace for #{namespace} not found"
end
end
def find_or_create_resource_for(name)
- resource_name = name.to_s.camelize
- ancestors = self.class.name.split("::")
- if ancestors.size > 1
- find_resource_in_modules(resource_name, ancestors)
+ resource_name = name.to_s.gsub(/^_/,'').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
rescue NameError
if self.class.const_defined?(resource_name)
@@ -112,10 +92,10 @@
case method_name.last
when "="
attributes[method_name.first(-1)] = arguments.first
when "?"
- attributes[method_name.first(-1)]
+ !attributes[method_name.first(-1)].blank?
when "]"
attributes[arguments.first.to_s]
else
attributes.has_key?(method_name) ? attributes[method_name] : super
end