# frozen_string_literal: true require 'creditsafe/errors' require 'creditsafe/camelizer_lower' module Creditsafe class BaseModel class << self def get(path, params = {}) result = Creditsafe.client.get(path.strip, params) raise APIKeyError, result.body[:error] if result.status == 401 result end def post(path, params = {}) result = Creditsafe.client.post(path.strip, params) raise APIKeyError, result.body[:error] if result.status == 401 result end def attributes(*attributes) @attributes ||= [] return @attributes unless attributes attr_accessor(*attributes) @attributes += attributes end def attribute_aliases(aliases = nil) @attribute_aliases ||= {} return @attribute_aliases unless aliases @attribute_aliases.merge!(aliases) end def format_url(url, params) formatted = url.dup.strip params.each { |key, value| formatted.sub!(":#{key}", value) } formatted end def successful_response?(result) result.status < 400 end def key_transformer CamelizerLower end # Sets all the instance variables by reading the JSON from Creditsafe and converting the keys # from camelCase to snake_case, as it's the standard in Ruby. def build(json: {}, key_transformer: self.key_transformer) new.tap do |record| attributes.each do |attr| key = attribute_aliases.key?(attr) ? attribute_aliases[attr] : attr record.public_send("#{attr}=", json[key_transformer.transform(key)]) end end end end def initialize(attributes = {}) attributes.each do |attr, value| public_send("#{attr}=", value) end end def get(path, params = {}) self.class.get(path, params) end def post(path, params = {}) self.class.post(path, params) end def format_url(url, params) self.class.format_url(url, params) end def as_json self.class.attributes.each_with_object({}) do |attr, hash| value = public_send(attr) value = value.as_json if value.respond_to?(:as_json) if value.is_a?(Array) value = value.map { |v| v.respond_to?(:as_json) ? v.as_json : v } end key = self.class.key_transformer.transform(attr) hash[key] = value end end end end