Sha256: a35e9e39674648fd55d88a0d747f5073d302908e10e76535751ff879008c2c11
Contents?: true
Size: 1.98 KB
Versions: 3
Compression:
Stored size: 1.98 KB
Contents
# frozen_string_literal: true module ZuoraConnectUi # Take a resource and dump it to Google Style JSON, really fast class Serializer def initialize(resource, options = {}) @resource = resource @kind = options[:kind] @fields = options[:fields] @is_collection = options[:is_collection] # TODO: if an attribute given is reserved, throw an error end def serialized_json require 'oj' # Enable to show Oj working in console # Oj.default_options = { trace: true } Oj.dump(serialized_hash, mode: :compat, time_format: :ruby) end def serialized_hash return hash_for_collection if collection?(@resource) hash_for_one end def hash_for_one hash = { data: nil } return hash unless @resource hash[:data] = record_hash(@resource) hash end def hash_for_collection hash = { data: {} } items = [] @resource.each do |resource| items << record_hash(resource) end hash[:data][:items] = items hash end private def key_transform(input) input.to_s.camelize(:lower) end def collection?(resource) return @is_collection unless @is_collection.nil? resource.respond_to?(:size) && !resource.respond_to?(:each_pair) end def record_hash(resource) hash = { kind: key_transform(@kind), id: resource.id } @fields.each do |field| hash[key_transform(field)] = resource.public_send(field) end hash end # TODO: hold reserved words # see https://google.github.io/styleguide/jsoncstyleguide.xml TOP_LEVEL_RESERVED = %w[ apiVersion context id method params data error ].freeze # Reserved fields in the Data object # kind the resource's type # fields comma separated list of attributes given # etag # items if @resource is a collection, then items is the array of resources DATA_RESERVED = %w[ kind fields etag items ].freeze end end
Version data entries
3 entries across 3 versions & 1 rubygems
Version | Path |
---|---|
zuora_connect_ui-0.10.2 | lib/zuora_connect_ui/serializer.rb |
zuora_connect_ui-0.10.1 | lib/zuora_connect_ui/serializer.rb |
zuora_connect_ui-0.10.0 | lib/zuora_connect_ui/serializer.rb |