Module: Sqreen::Kit::Signals::DtoHelper

Included in:
Actor, Context::HttpContext, Location, LocationInfra, SignalAttributes
Defined in:
lib/sqreen/kit/signals/dto_helper.rb

Overview

Provides a helper constructor, default to_h, and mandatory field checking

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

DO_NOT_CONVERT_TYPES =
[
  NilClass, Hash, Array, Numeric, TrueClass, FalseClass
].freeze
RFC_3339_FMT =
'%Y-%m-%dT%H:%M:%S.%3N%:z'.freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(mod) ⇒ Object



114
115
116
# File 'lib/sqreen/kit/signals/dto_helper.rb', line 114

def self.included(mod)
  mod.extend(ClassMethods)
end

Instance Method Details

#append_to_h_filter(proc) ⇒ Object



144
145
146
147
# File 'lib/sqreen/kit/signals/dto_helper.rb', line 144

def append_to_h_filter(proc)
  @filters ||= []
  @filters << proc
end

#compact_hash(h) ⇒ Object



124
125
126
# File 'lib/sqreen/kit/signals/dto_helper.rb', line 124

def compact_hash(h)
  h.delete_if { |_k, v| v.nil? }
end

#initialize(values = {}) ⇒ Object



118
119
120
121
122
# File 'lib/sqreen/kit/signals/dto_helper.rb', line 118

def initialize(values = {})
  values.each do |attr, val|
    public_send("#{attr}=", val)
  end
end

#to_hObject



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/sqreen/kit/signals/dto_helper.rb', line 128

def to_h
  check_mandatories

  res = {}
  self.class.attributes_for_to_h.each do |attr|
    value = public_send(attr)
    if (value.class.ancestors & DO_NOT_CONVERT_TYPES).empty? && \
       value.respond_to?(:to_h)
      value = value.to_h
    end

    res[attr] = value unless value.nil?
  end
  res
end

#to_jsonObject



149
150
151
152
153
154
# File 'lib/sqreen/kit/signals/dto_helper.rb', line 149

def to_json
  return to_h.to_json unless instance_variable_defined?(:@filters)

  res = @filters.reduce(to_h) { |accum, filter| filter[accum] }
  res.to_json
end