Module: Eazypi::Serializer

Extended by:
ActiveSupport::Concern
Defined in:
lib/eazypi/serializer.rb

Overview

A serializer you can use to define your own Object types easily

Defined Under Namespace

Classes: Attribute

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.serialize_object(type_object, object) ⇒ Object

rubocop:disable Metrics/MethodLength



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/eazypi/serializer.rb', line 101

def self.serialize_object(type_object, object) # rubocop:disable Metrics/MethodLength
  if type_object.nil?
    nil
  elsif type_object.is_a?(Array)
    object&.map do |value|
      serialize_object(type_object[0], value)
    end
  elsif [Date, Time].include?(type_object)
    object&.iso8601
  elsif [String, Integer, Float, :boolean].include?(type_object)
    object
  else
    type_object.new(object).to_json
  end
end

Instance Method Details

#initialize(object) ⇒ Object



53
54
55
# File 'lib/eazypi/serializer.rb', line 53

def initialize(object)
  @object = object
end

#to_json(*_args) ⇒ Object



57
58
59
60
61
62
63
# File 'lib/eazypi/serializer.rb', line 57

def to_json(*_args)
  return nil if @object.nil?

  self.class.attributes.to_h do |attribute|
    [attribute.name, attribute.serialize(@object)]
  end
end