Class: Sneakers::ContentType

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(serializer, deserializer) ⇒ ContentType

Returns a new instance of ContentType.



38
39
40
41
# File 'lib/sneakers/content_type.rb', line 38

def initialize(serializer, deserializer)
  @serializer = serializer
  @deserializer = deserializer
end

Instance Attribute Details

#deserializerObject (readonly)

Returns the value of attribute deserializer.



43
44
45
# File 'lib/sneakers/content_type.rb', line 43

def deserializer
  @deserializer
end

#serializerObject (readonly)

Returns the value of attribute serializer.



43
44
45
# File 'lib/sneakers/content_type.rb', line 43

def serializer
  @serializer
end

Class Method Details

.deserialize(payload, content_type) ⇒ Object



23
24
25
26
# File 'lib/sneakers/content_type.rb', line 23

def self.deserialize(payload, content_type)
  return payload unless content_type
  @_types[content_type].deserializer.(payload)
end

.passthroughObject



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

def self.passthrough
  ->(payload) { payload }
end

.register(content_type: nil, serializer: nil, deserializer: nil) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/sneakers/content_type.rb', line 3

def self.register(content_type: nil, serializer: nil, deserializer: nil)
  # This can be removed when support is dropped for ruby 2.0 and replaced
  # by a keyword arg with no default value
  fail ArgumentError, 'missing keyword: content_type' if content_type.nil?
  fail ArgumentError, 'missing keyword: serializer' if serializer.nil?
  fail ArgumentError, 'missing keyword: deserializer' if deserializer.nil?

  fail ArgumentError, "#{content_type} serializer must be a proc" unless serializer.is_a? Proc
  fail ArgumentError, "#{content_type} deserializer must be a proc" unless deserializer.is_a? Proc

  fail ArgumentError, "#{content_type} serializer must accept one argument, the payload" unless serializer.arity == 1
  fail ArgumentError, "#{content_type} deserializer must accept one argument, the payload" unless deserializer.arity == 1
  @_types[content_type] = new(serializer, deserializer)
end

.reset!Object



28
29
30
31
32
# File 'lib/sneakers/content_type.rb', line 28

def self.reset!
  @_types = Hash.new(
    new(passthrough, passthrough)
  )
end

.serialize(payload, content_type) ⇒ Object



18
19
20
21
# File 'lib/sneakers/content_type.rb', line 18

def self.serialize(payload, content_type)
  return payload unless content_type
  @_types[content_type].serializer.(payload)
end