Commit a417b0f

mokha <mokha@cisco.com>
2018-05-14 21:16:56
attempt to map body using content type header.
1 parent 64f0138
lib/net/hippie/client.rb
@@ -20,7 +20,7 @@ module Net
         @certificate = certificate
         @default_headers = headers
         @key = key
-        @mapper = JsonMapper.new
+        @mapper = ContentTypeMapper.new
         @passphrase = passphrase
         @verify_mode = verify_mode
       end
@@ -70,8 +70,9 @@ module Net
       end
 
       def request_for(type, uri, headers: {}, body: {})
-        type.new(uri, default_headers.merge(headers)).tap do |x|
-          x.body = mapper.map_from(body) unless body.empty?
+        final_headers = default_headers.merge(headers)
+        type.new(uri, final_headers).tap do |x|
+          x.body = mapper.map_from(final_headers, body) unless body.empty?
         end
       end
 
lib/net/hippie/content_type_mapper.rb
@@ -0,0 +1,12 @@
+module Net
+  module Hippie
+    # Converts a ruby hash into a JSON string
+    class ContentTypeMapper
+      def map_from(headers, body)
+        content_type = headers['Content-Type'] || ''
+        return JSON.generate(body) if content_type.include?("json")
+        body
+      end
+    end
+  end
+end
lib/net/hippie/json_mapper.rb
@@ -1,10 +0,0 @@
-module Net
-  module Hippie
-    # Converts a ruby hash into a JSON string
-    class JsonMapper
-      def map_from(hash)
-        JSON.generate(hash)
-      end
-    end
-  end
-end
lib/net/hippie.rb
@@ -4,7 +4,7 @@ require 'net/http'
 require 'openssl'
 
 require 'net/hippie/version'
-require 'net/hippie/json_mapper'
+require 'net/hippie/content_type_mapper'
 require 'net/hippie/client'
 require 'net/hippie/api'
 
test/net/content_type_mapper_test.rb
@@ -0,0 +1,27 @@
+require 'test_helper'
+
+class ContentTypeMapperTest < Minitest::Test
+  def test_returns_json
+    subject = Net::Hippie::ContentTypeMapper.new
+    headers = { 'Content-Type' => 'application/json' }
+    body = { message: 'something witty' }
+    result = subject.map_from(headers, body)
+    assert_equal JSON.generate(body), result
+  end
+
+  def test_returns_json_with_charset
+    subject = Net::Hippie::ContentTypeMapper.new
+    headers = { 'Content-Type' => 'application/json; charset=utf-8' }
+    body = { message: 'something witty' }
+    result = subject.map_from(headers, body)
+    assert_equal JSON.generate(body), result
+  end
+
+  def test_return_html
+    subject = Net::Hippie::ContentTypeMapper.new
+    headers = { 'Content-Type' => 'text/html' }
+    body = "<html></html>"
+    result = subject.map_from(headers, body)
+    assert_equal body, result
+  end
+end