Class: GovKit::Resource

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
lib/gov_kit/resource.rb

Overview

This is the parent class for the classes that wrap the data returned to govkit.

Subclasses are responsible for fetching the data from different web services; Resource will then parse the returned data, converting returned fields to instance methods.

Initialize a Resource with a hash of attributes, or an array of hashes. For each attribute, add a getter and setter to this instance. Includes HTTParty, which provides convenience methods like get().

Examples:

res = Resource.new { "aaa" => "111", "bbb" => "222", "ccc" => "333" }
res.aaa == "111"
res.bbb == "222"
res.ccc == "333"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Resource

Returns a new instance of Resource.



30
31
32
33
34
35
# File 'lib/gov_kit/resource.rb', line 30

def initialize(attributes = {})
  @attributes = {}
  @raw_response = attributes

  unload(attributes)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_symbol, *arguments) ⇒ Object (private)

:nodoc:



175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/gov_kit/resource.rb', line 175

def method_missing(method_symbol, * arguments) #:nodoc:
  method_name = method_symbol.to_s

  case method_name.last
    when "="
      attributes[method_name.first(-1)] = arguments.first
    when "?"
      !attributes[method_name.first(-1)].blank?
    when "]"
      attributes[arguments.first.to_s]
    else
      attributes.has_key?(method_name) ? attributes[method_name] : super
  end
end

Instance Attribute Details

#attributesObject (readonly)

The attributes data returned by the service.



25
26
27
# File 'lib/gov_kit/resource.rb', line 25

def attributes
  @attributes
end

#raw_responseObject (readonly)

The response returned by the service.



28
29
30
# File 'lib/gov_kit/resource.rb', line 28

def raw_response
  @raw_response
end

Class Method Details

.instantiate(record) ⇒ Resource

Instantiate new GovKit::Resources.

If record is a hash, return a single GovKit::Resource. If it is an array, return an array of GovKit::Resources.

Parameters:

  • record (Hash)

    a hash of values returned by a service, or an array of hashes.

Returns:



83
84
85
86
87
88
89
# File 'lib/gov_kit/resource.rb', line 83

def self.instantiate(record)
  if record.is_a?(Array)
    instantiate_collection(record)
  else
    new(record)
  end
end

.instantiate_collection(collection) ⇒ Array

Instantiate a set of records.

Parameters:

  • collection (Array)

    An array of records

Returns:

  • (Array)

    Array of records



95
96
97
# File 'lib/gov_kit/resource.rb', line 95

def self.instantiate_collection(collection)
  collection.collect! { |record| new(record) }
end

.parse(response) ⇒ Resource

Handles the basic responses we might get back from a web service.

On failure, throws an error.

If a service returns something other than a 404 when an object is not found, you’ll need to handle that in the subclass.

Parameters:

  • response (Object)

    the object.

Returns:

  • (Resource)

    a new Resource created from the response.



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/gov_kit/resource.rb', line 53

def self.parse(response)

  if response.class == HTTParty::Response
    case response.response
      when Net::HTTPNotFound
        raise ResourceNotFound, "404 Not Found"
      when Net::HTTPGone
        raise ResourceNotFound, "404 Not Found"
      when Net::HTTPUnauthorized
        raise NotAuthorized, "401 Not Authorized; have you set up your API key?"
      when Net::HTTPServerError
        raise ServerError, '5xx server error'
      when Net::HTTPClientError
        raise ClientError, '4xx client error'
    end
  end

  return [] unless !response.blank?

  instantiate(response)
end

Instance Method Details

#to_md5Hash

Returns the response object, potentially useful for comparison on sync.

Returns:

  • (Hash)

    the response object, potentially useful for comparison on sync



39
40
41
# File 'lib/gov_kit/resource.rb', line 39

def to_md5
  Digest::MD5.hexdigest(@raw_response.body)
end

#unload(attributes) ⇒ Object

Given a hash of attributes, assign it to the @attributes member. Then for each attribute, create or set a pair of member accessors with the name of the attribute’s key.

If the value of the attribute is itself an array or a hash, then create a new class with the (singularized) key as a name, and with a parent class of Resource, and initialize it with the hash.

Parameters:

  • attributes (Hash)

    the attributes returned by the web service.

Raises:

  • (ArgumentError)


109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/gov_kit/resource.rb', line 109

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)
          value.map do |attrs|
            if attrs.is_a?(String) || attrs.is_a?(Numeric)
              attrs.duplicable? ? attrs.dup : attrs
            else
              resource.new(attrs)
            end
          end
        when Hash
          resource = find_or_create_resource_for(key)
          resource.new(value)
        else
          value.dup rescue value
      end
  end
  self
end