Sha256: ac3cc93a0a61cde23a3be183d423df2bab0711a0598bb4e0862157134639ae66

Contents?: true

Size: 1.09 KB

Versions: 4

Compression:

Stored size: 1.09 KB

Contents

module OMCMS
  module Response
    class Error < StandardError
      attr_reader :status

      def initialize response
        return unless response
        unless response.respond_to? :body
          response = add_body_to_error(response)
        end

        response.body.each do |key, value|
          instance_variable_set("@#{key}", value)
          self.class.send(:attr_reader, key)
        end
      end

      def to_json
        self.instance_variables.map do |attribute|
          key = attribute.to_s.gsub('@','')
          [snakecase(key), self.instance_variable_get(attribute)]
        end.to_h
      end

      private

      def add_body_to_error(response)
        OpenStruct.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

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
omcms-ruby-client-1.2.0 lib/omcms/response/error.rb
omcms-ruby-client-1.1.0 lib/omcms/response/error.rb
omcms-ruby-client-1.0.3 lib/omcms/response/error.rb
omcms-ruby-client-1.0.2 lib/omcms/response/error.rb