# frozen_string_literal: true module OMCMS module Response class Error < StandardError attr_reader :status def initialize(response) super return unless response response = add_body_to_error(response) unless response.respond_to? :body response.body.each do |key, value| instance_variable_set("@#{key}", value) self.class.send(:attr_reader, key) end end def to_json(*_args) instance_variables.to_h do |attribute| key = attribute.to_s.gsub("@", "") [snakecase(key), instance_variable_get(attribute)] end end private def add_body_to_error(response) Struct.new( body: { name: response.class, message: response.message, data: response } ) end def snakecase(data = "") data.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2') .gsub(/([a-z\d])([A-Z])/, '\1_\2') .tr("-", "_") .gsub(/\s/, "_") .gsub(/__+/, "_") .downcase end end end end