lib/redfish_client/resource.rb in redfish_client-0.2.1 vs lib/redfish_client/resource.rb in redfish_client-0.2.2
- old
+ new
@@ -22,33 +22,38 @@
class Resource
# NoODataId error is raised when operation would need OpenData id of the
# resource to accomplish the task a hand.
class NoODataId < StandardError; end
+ # NoResource error is raised if the service cannot find requested
+ # resource.
+ class NoResource < StandardError; end
+
+ # Headers, returned from the service when resource has been constructed.
+ attr_reader :headers
+
# Create new resource.
#
# Resource can be created either by passing in OpenData identifier or
# supplying the content (hash). In the first case, connector will be used
# to fetch the resource data. In the second case, resource only wraps the
# passed-in hash and does no fetching.
#
# @param connector [RedfishClient::Connector] connector that will be used
# to fetch the resources
# @param oid [String] OpenData id of the resource
- # @param content [Hash]
+ # @param content [Hash] content to populate resource with
+ # @raise [NoResource] resource cannot be retrieved from the service
def initialize(connector, oid: nil, content: nil)
+ @cache = {}
+ @connector = connector
+
if oid
- resp = connector.get(oid)
- @content = JSON.parse(resp.data[:body])
- @content["@odata.id"] = oid
- @headers = resp.data[:headers]
+ initialize_from_service(oid)
else
@content = content
end
-
- @cache = {}
- @connector = connector
end
# Access resource content.
#
# This function offers a way of accessing resource data in the same way
@@ -134,11 +139,11 @@
# @param path [String] path to post to
# @param payload [Hash<String, >] data to send
# @return [Excon::Response] response
# @raise [NoODataId] resource has no OpenData id
def post(field: "@odata.id", path: nil, payload: nil)
- @connector.post(get_path(field, path), payload ? payload.to_json : "")
+ @connector.post(get_path(field, path), payload)
end
# Issue a PATCH requests to the selected endpoint.
#
# Works exactly the same as the {post} method, but issued a PATCH request
@@ -148,11 +153,11 @@
# @param path [String] path to patch
# @param payload [Hash<String, >] data to send
# @return [Excon::Response] response
# @raise [NoODataId] resource has no OpenData id
def patch(field: "@odata.id", path: nil, payload: nil)
- @connector.patch(get_path(field, path), payload ? payload.to_json : "")
+ @connector.patch(get_path(field, path), payload)
end
# Issue a DELETE requests to the endpoint of the resource.
#
# If the resource has no `@odata.id` field, {NoODataId} error will be
@@ -164,9 +169,18 @@
def delete
@connector.delete(get_path("@odata.id", nil))
end
private
+
+ def initialize_from_service(oid)
+ resp = @connector.get(oid)
+ raise NoResource unless resp.status == 200
+
+ @content = JSON.parse(resp.data[:body])
+ @content["@odata.id"] = oid
+ @headers = resp.data[:headers]
+ end
def get_path(field, path)
raise NoODataId if path.nil? && !key?(field)
path || @content[field]
end