Class: ZuoraConnectUi::Serializer

Inherits:
Object
  • Object
show all
Defined in:
lib/zuora_connect_ui/serializer.rb,
lib/zuora_connect_ui/serializer/relationship.rb

Overview

Take a resource and dump it to Google Style JSON, really fast

Defined Under Namespace

Classes: Relationship

Instance Method Summary collapse

Constructor Details

#initialize(resource, options = {}) ⇒ Serializer

Returns a new instance of Serializer.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/zuora_connect_ui/serializer.rb', line 9

def initialize(resource, options = {})
  @resource = resource
  @kind = options[:kind]
  @is_collection = options[:is_collection]

  @record_type = parse_record_type(@kind, @resource)
  @camel_type = key_transform(@record_type)
  @cache_keys = {}

  @associations = parse_associations(
    options[:has_many], options[:belongs_to], options[:has_one]
  )

  @fields = parse_fields(options[:fields])

  # TODO: if an attribute given is reserved, throw an error
end

Instance Method Details

#hash_for_collectionObject



54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/zuora_connect_ui/serializer.rb', line 54

def hash_for_collection
  hash = { data: { items: [] } }

  @resource.each do |resource|
    hash[:data][:items] << record_hash(resource, @record_type)
  end

  return hash if @associations.empty?

  hash[:data][:relationships] = get_associations(@resource)

  hash
end

#hash_for_oneObject



40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/zuora_connect_ui/serializer.rb', line 40

def hash_for_one
  hash = { data: nil }

  return hash unless @resource

  hash[:data] = record_hash(@resource, @record_type)

  return hash if @associations.empty?

  hash[:data][:relationships] = get_associations([@resource])

  hash
end

#serializable_hashObject



34
35
36
37
38
# File 'lib/zuora_connect_ui/serializer.rb', line 34

def serializable_hash
  return hash_for_collection if collection?(@resource)

  hash_for_one
end

#serialized_jsonObject



27
28
29
30
31
32
# File 'lib/zuora_connect_ui/serializer.rb', line 27

def serialized_json
  require 'oj'
  # Enable to show Oj working in console
  # Oj.default_options = { trace: true }
  Oj.dump(serializable_hash, mode: :compat, time_format: :ruby)
end