Class: FunWithJsonApi::FindResourceFromDocument

Inherits:
Object
  • Object
show all
Defined in:
lib/fun_with_json_api/find_resource_from_document.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(document, deserializer) ⇒ FindResourceFromDocument

Returns a new instance of FindResourceFromDocument.



12
13
14
15
# File 'lib/fun_with_json_api/find_resource_from_document.rb', line 12

def initialize(document, deserializer)
  @document = FunWithJsonApi.sanitize_document(document)
  @deserializer = deserializer
end

Instance Attribute Details

#deserializerObject (readonly)

Returns the value of attribute deserializer.



10
11
12
# File 'lib/fun_with_json_api/find_resource_from_document.rb', line 10

def deserializer
  @deserializer
end

#documentObject (readonly)

Returns the value of attribute document.



9
10
11
# File 'lib/fun_with_json_api/find_resource_from_document.rb', line 9

def document
  @document
end

Class Method Details

.findObject



3
4
5
# File 'lib/fun_with_json_api/find_resource_from_document.rb', line 3

def self.find(...)
  new(...).find
end

Instance Method Details

#document_idObject



30
31
32
# File 'lib/fun_with_json_api/find_resource_from_document.rb', line 30

def document_id
  @document_id ||= document['data']['id']
end

#document_is_null_resource?Boolean

Returns:

  • (Boolean)


48
49
50
# File 'lib/fun_with_json_api/find_resource_from_document.rb', line 48

def document_is_null_resource?
  document['data'].nil?
end

#document_is_valid?Boolean

Returns:

  • (Boolean)


42
43
44
45
46
# File 'lib/fun_with_json_api/find_resource_from_document.rb', line 42

def document_is_valid?
  document.key?('data') && (
    document['data'].is_a?(Hash) || document_is_null_resource?
  )
end

#document_matches_resource_type?Boolean

Returns:

  • (Boolean)


52
53
54
# File 'lib/fun_with_json_api/find_resource_from_document.rb', line 52

def document_matches_resource_type?
  resource_type == document_type
end

#document_typeObject



34
35
36
# File 'lib/fun_with_json_api/find_resource_from_document.rb', line 34

def document_type
  @document_type ||= document['data']['type']
end

#findObject



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/fun_with_json_api/find_resource_from_document.rb', line 17

def find
  raise build_invalid_document_error unless document_is_valid?

  # Resource is being set to nil/null
  return nil if document_is_null_resource?

  # Ensure the document matches the expected resource
  raise build_invalid_document_type_error unless document_matches_resource_type?

  # Load resource from id value
  load_resource_and_check!
end

#resource_typeObject



38
39
40
# File 'lib/fun_with_json_api/find_resource_from_document.rb', line 38

def resource_type
  @resource_type ||= deserializer.type
end