Sha256: 19cb8f2eeac93784c29f57cb98c079d21da535a4dfb12d4f88a4d0bae22f10db

Contents?: true

Size: 1.23 KB

Versions: 3

Compression:

Stored size: 1.23 KB

Contents

require 'json'

module RapidsRivers

  # Understands a specifc message
  class Packet
    # The following keys are reserved for system usage:
    VISIT_COUNT = 'system_read_count'
    CONTRIBUTING_SERVICES = 'contributing_services'

    attr_reader :contributing_services, :system_read_count
    protected :contributing_services

    def initialize(json_hash)
      @json_hash = json_hash
      @system_read_count = (@json_hash[VISIT_COUNT] || -1) + 1
      @contributing_services = @json_hash[CONTRIBUTING_SERVICES] || []
      @used_keys = [VISIT_COUNT, CONTRIBUTING_SERVICES]
    end

    def used_key(key)
      @used_keys << key.to_s
    end

    def clone_with_name(service_name)
      self.clone.tap { |packet_copy| packet_copy.contributing_services << service_name }
    end

    def to_json
      update_hash
      @json_hash.to_json
    end

    def to_s
      "Packet (in JSON): #{self.to_json}"
    end

    def pretty_print
      update_hash
      JSON.pretty_generate @json_hash
    end

    private

      def update_hash
        @used_keys.each do |key|
          value = instance_variable_get("@#{key}".to_sym)
          @json_hash[key] = value if value
        end
      end

  end

end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rapids_rivers-0.2.16 lib/rapids_rivers/packet.rb
rapids_rivers-0.2.14 lib/rapids_rivers/packet.rb
rapids_rivers-0.2.9 lib/rapids_rivers/packet.rb