lib/fortnox/api/models/base.rb in fortnox-api-0.8.0 vs lib/fortnox/api/models/base.rb in fortnox-api-0.8.1
- old
+ new
@@ -1,10 +1,11 @@
# frozen_string_literal: true
-require 'fortnox/api/types'
require 'ice_nine'
+require_relative '../types'
+
module Fortnox
module API
module Model
class Base < Fortnox::API::Types::Model
# TODO(jonas): Restructure this class a bit, it is not very readable.
@@ -34,10 +35,14 @@
def self.stub
new(self::STUB.dup)
end
+ def unique_id
+ send(self.class::UNIQUE_ID)
+ end
+
# This filtering logic could be improved since it is currently O(N*M).
def attributes(*options)
return self.class.schema if options.nil?
options = Array(options)
@@ -45,12 +50,17 @@
self.class.schema.find_all do |_name, attribute|
options.all? { |option| attribute.is?(option) }
end
end
- def unique_id
- send(self.class::UNIQUE_ID)
+ def to_hash(recursive = false)
+ return super() if recursive
+
+ self.class.schema.each_with_object({}) do |key, result|
+ # Only output attributes that have a value set
+ result[key.name] = self[key.name] if self.send("#{key.name}?")
+ end
end
def update(hash)
old_attributes = to_hash
new_attributes = old_attributes.merge(hash)
@@ -83,22 +93,12 @@
def parent
@parent || self.class.new(self.class::STUB.dup)
end
- def to_hash(recursive = false)
- return super() if recursive
-
- self.class.schema.keys.each_with_object({}) do |key, result|
- result[key] = self[key]
- end
- end
-
- private_class_method
-
# dry-types filter anything that isn't specified as an attribute on the
# class that is being instantiated. This wrapper preserves the meta
- # properties we need to track object state during that initilisation and
+ # properties we need to track object state during that initialisation and
# sets them on the object after dry-types is done with it.
def self.preserve_meta_properties(hash)
is_unsaved = hash.delete(:unsaved) { true }
is_new = hash.delete(:new) { true }
parent = hash.delete(:parent) { nil }