Sha256: 0d4e0937bf83063223c382a3ed88ff31ff9e4e7f1ccb17a4ff0f6f4ce4b1b4a6

Contents?: true

Size: 1.13 KB

Versions: 13

Compression:

Stored size: 1.13 KB

Contents

module RESTinPeace
  class ResponseConverter
    class UnknownConvertStrategy < RESTinPeace::DefaultError
      def initialize(klass)
        super("Don't know how to convert #{klass}")
      end
    end

    attr_accessor :body, :klass, :existing_instance

    def initialize(response, instance_or_class)
      self.body = response.body

      if instance_or_class.respond_to?(:new)
        self.klass = instance_or_class
        self.existing_instance = new_instance
      else
        self.klass = instance_or_class.class
        self.existing_instance = instance_or_class
      end
    end

    def result
      case body.class.to_s
      when 'Array'
        convert_from_array
      when 'Hash'
        convert_from_hash
      when 'String'
        body
      else
        raise UnknownConvertStrategy, body.class
      end
    end

    def convert_from_array
      body.map do |entity|
        convert_from_hash(entity, new_instance)
      end
    end

    def convert_from_hash(entity = body, instance = existing_instance)
      instance.force_attributes_from_hash entity
      instance
    end

    def new_instance
      klass.new
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
rest-in-peace-5.0.1 lib/rest_in_peace/response_converter.rb
rest-in-peace-5.0.0 lib/rest_in_peace/response_converter.rb
rest-in-peace-4.2.1 lib/rest_in_peace/response_converter.rb
rest-in-peace-4.2.0 lib/rest_in_peace/response_converter.rb
rest-in-peace-4.1.1 lib/rest_in_peace/response_converter.rb
rest-in-peace-4.1.0 lib/rest_in_peace/response_converter.rb
rest-in-peace-4.0.0 lib/rest_in_peace/response_converter.rb
rest-in-peace-3.0.0 lib/rest_in_peace/response_converter.rb
rest-in-peace-2.0.4 lib/rest_in_peace/response_converter.rb
rest-in-peace-2.0.3 lib/rest_in_peace/response_converter.rb
rest-in-peace-2.0.2 lib/rest_in_peace/response_converter.rb
rest-in-peace-2.0.1 lib/rest_in_peace/response_converter.rb
rest-in-peace-2.0.0 lib/rest_in_peace/response_converter.rb