Class: Hx::Interop::ContentType

Inherits:
Object
  • Object
show all
Defined in:
lib/interop/content_type.rb

Overview

A marshaler that corresponds to a content-type string.

Constant Summary collapse

STANDARD =
ContentTypes.new
JSON =
STANDARD.register('application/json', ::JSON)
BINARY =
STANDARD.register('application/octet-stream', Marshaler::NULL)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, marshaler) ⇒ ContentType

Returns a new instance of ContentType.



11
12
13
14
15
16
17
18
19
20
# File 'lib/interop/content_type.rb', line 11

def initialize(name, marshaler)
  name.is_a? String or
    raise ArgumentError, 'Expected name to be a string'

  %i[load dump].all?(&marshaler.method(:respond_to?)) or
    raise ArgumentError, 'Expected marshaler to respond to :load and :dump'

  @name = -name
  @marshaler = marshaler
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



9
10
11
# File 'lib/interop/content_type.rb', line 9

def name
  @name
end

Instance Method Details

#decode(message) ⇒ Object



30
31
32
# File 'lib/interop/content_type.rb', line 30

def decode(message)
  load message.body
end

#dump(obj) ⇒ Object



26
27
28
# File 'lib/interop/content_type.rb', line 26

def dump(obj)
  @marshaler.dump obj
end

#encode(obj) ⇒ Object



34
35
36
# File 'lib/interop/content_type.rb', line 34

def encode(obj)
  Message.new.tap { |m| encode_to obj, m }
end

#encode_to(obj, message) ⇒ Object



38
39
40
41
42
43
44
45
# File 'lib/interop/content_type.rb', line 38

def encode_to(obj, message)
  body         = dump(obj)
  message.body = body
  message.headers.merge!(
    Headers::CONTENT_TYPE   => name,
    Headers::CONTENT_LENGTH => body.bytesize
  )
end

#load(str) ⇒ Object



22
23
24
# File 'lib/interop/content_type.rb', line 22

def load(str)
  @marshaler.load str
end