lib/fulfil_api/resource.rb in fulfil_api-0.0.3 vs lib/fulfil_api/resource.rb in fulfil_api-0.1.0
- old
+ new
@@ -3,13 +3,21 @@
module FulfilApi
# The {FulfilApi::Resource} represents a single resource returned by the API
# endpoints of Fulfil.
class Resource
include AttributeAssignable
+ include Persistable
+ class ModelNameMissing < Error; end
+
def initialize(attributes = {})
+ attributes.deep_stringify_keys!
+
@attributes = {}.with_indifferent_access
+ @model_name = attributes.delete("model_name").presence ||
+ raise(ModelNameMissing, "The model name is missing. Use the :model_name attribute to define it.")
+
assign_attributes(attributes)
end
class << self
delegate_missing_to :relation
@@ -21,11 +29,11 @@
# @note it makes use of the {.delegate_missing_to} method from {ActiveSupport}
# to ensure that all unknown class methods for the {FulfilApi::Resource} are
# forwarded to the {FulfilApi::Resource.relation}.
#
# @example forwarding of the .where class method
- # FulfilApi::Resource.set(name: "sale.sale").find_by(["id", "=", 100])
+ # FulfilApi::Resource.set(model_name: "sale.sale").find_by(["id", "=", 100])
#
# @return [FulfilApi::Resource::Relation]
def relation
Relation.new(self)
end
@@ -37,13 +45,32 @@
# @return [Any, nil]
def [](attribute_name)
@attributes[attribute_name]
end
+ # Builds a structure for keeping track of any errors when trying to use the
+ # persistance methods for the API resource.
+ #
+ # @return [FulfilApi::Resource::Errors]
+ def errors
+ @errors ||= Errors.new(self)
+ end
+
+ # The {#id} is a shorthand to easily grab the ID of an API resource.
+ #
+ # @return [Integer, nil]
+ def id
+ @attributes["id"]
+ end
+
# Returns all currently assigned attributes for a {FulfilApi::Resource}.
#
# @return [Hash]
def to_h
@attributes
end
+
+ private
+
+ attr_reader :model_name
end
end