# frozen_string_literal: true require 'credit_gateway/errors' require 'credit_gateway/camelizer_lower' module CreditGateway class BaseModel class << self 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 key_transformer CamelizerLower end # Sets all the instance variables by reading the JSON from CreditGateway and converting the keys from # PascalCase 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 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 value = value.iso8601 if value.respond_to?(:iso8601) key = self.class.key_transformer.transform(attr) hash[key] = value end end end end