From e7beb2c298036e26a4c5c41a191509bc672caa5a Mon Sep 17 00:00:00 2001 From: Alexander Olofsson <alexander.olofsson@liu.se> Date: Mon, 14 Aug 2023 13:20:53 +0200 Subject: [PATCH] Separate model data conversion methods This allows storing the data in its expected format outside of CMDB calls --- lib/liudesk_cmdb/model.rb | 52 ++++++++++++++++++++++++--------------- 1 file changed, 32 insertions(+), 20 deletions(-) diff --git a/lib/liudesk_cmdb/model.rb b/lib/liudesk_cmdb/model.rb index b97fc9f..6f6e412 100644 --- a/lib/liudesk_cmdb/model.rb +++ b/lib/liudesk_cmdb/model.rb @@ -128,6 +128,36 @@ module LiudeskCMDB superclass.fields.merge(@fields || {}) end + def convert_cmdb_to_ruby(data) + fields.each do |key, attributes| + next unless data[key] + + case attributes[:convert].to_s + when Time.to_s + data[key] = Time.parse(data[key]).round + when Symbol.to_s + data[key] = data[key].to_sym + end + end + + data + end + + def convert_ruby_to_cmdb(data) + fields.each do |key, attributes| + next unless data.key? key + + case attributes[:convert].to_s + when Time.to_s + data[key] = data[key].utc.round.strftime("%FT%T.%LZ") if data[key].is_a? Time + when Symbol.to_s + data[key] = data[key].to_s if data[key].is_a? Symbol + end + end + + data + end + protected def read_fields(*fields) @@ -266,16 +296,7 @@ module LiudeskCMDB data = data.dup write_fields = self.class.fields.select { |_, field| field[:access].to_s.end_with?("write") }.map { |k, _| k } - self.class.fields.each do |key, attributes| - next unless data.key? key - - case attributes[:convert].to_s - when Time.to_s - data[key] = data[key].utc.round.strftime("%FT%T.%LZ") if data[key].is_a? Time - when Symbol.to_s - data[key] = data[key].to_s if data[key].is_a? Symbol - end - end + self.class.convert_ruby_to_cmdb(data) data.select { |k, _| write_fields.include?(k) }.transform_keys { |k| self.class.fields.dig(k, :name) } end @@ -291,16 +312,7 @@ module LiudeskCMDB @data = {} unless merge @data.merge!(converted) - self.class.fields.each do |key, attributes| - next unless @data[key] - - case attributes[:convert].to_s - when Time.to_s - @data[key] = Time.parse(@data[key]).round - when Symbol.to_s - @data[key] = @data[key].to_sym - end - end + self.class.convert_cmdb_to_ruby(@data) @retrieved = Time.now self -- GitLab