Sha256: d0744b43a0792a6ce39750f9c72ac4a43c987dc1c29ad71d311350876dd28fb6

Contents?: true

Size: 1.28 KB

Versions: 1

Compression:

Stored size: 1.28 KB

Contents

# frozen_string_literal: true

require 'json'

module Immoscout
  module Models
    module Concerns
      module Modelable
        extend ActiveSupport::Concern

        included do
          cattr_accessor :json_wrapper, :unpack_collection
          cattr_reader :api, instance_accessor: false do
            Immoscout::Api::Client.instance
          end

          def api
            self.class.api
          end

          def handle_response(response)
            self.class.handle_response(response)
          end

          def id_from_response(response)
            self.class.id_from_response(response)
          end
        end

        class_methods do
          def unpack(hash)
            hash.values.first
          end

          def from_raw(raw_hash)
            hash = raw_hash.is_a?(String) ? JSON.parse(raw_hash) : raw_hash
            new(unpack(hash))
          end

          def handle_response(response)
            return response if response.success?

            raise Immoscout::Errors::Failed, response
          end

          def id_from_response(response)
            response
              .body
              .fetch('common.messages')
              .first
              .fetch('message', {})
              .fetch('id', nil)
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
immoscout-1.3.2 lib/immoscout/models/concerns/modelable.rb