Sha256: 67af38242cdca85c466aa4892c558ab6518076e963bceb3c8de02e40cb47dd45

Contents?: true

Size: 1.34 KB

Versions: 2

Compression:

Stored size: 1.34 KB

Contents

# frozen_string_literal: true

require "dry-transformer"

module DjiMqttConnect
  module Utils
    # Provides methods for transforming data for a marshal to dump
    module MessageDumping
      # Renames the method attribute
      class MessageTransformer < Dry::Transformer::Pipe
        import Dry::Transformer::HashTransformations

        define! do
          rename_keys _method: :method
        end
      end

      private

      # Converts a DjiMqttConnect::Message to a serializeable hash
      def convert_message_to_hash(message)
        # Fix up the hash representation
        transformed_message = message_transformer.call(message)

        # Convert the transformed message into JSON-compatible data
        convert_to_serializable_object(transformed_message)
      end

      # Converts an object to a mqtt serializable object
      def convert_to_serializable_object(object)
        case object
        when Hash
          object.transform_values { |value| convert_to_serializable_object(value) }
        when Array
          object.map { |value| convert_to_serializable_object(value) }
        when BigDecimal
          # DJI expects floats, not string decimals
          object.to_f
        else
          object
        end
      end

      def message_transformer
        @message_transformer ||= MessageTransformer.new
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
dji_mqtt_connect-0.1.25.1 lib/dji_mqtt_connect/utils/message_dumping.rb
dji_mqtt_connect-0.1.25 lib/dji_mqtt_connect/utils/message_dumping.rb