Sha256: 68747586df064761e352f6ed582ceef699c9918018312f2fd07644476f354366

Contents?: true

Size: 1.72 KB

Versions: 3

Compression:

Stored size: 1.72 KB

Contents

require "hashie"
require "json"
require "yaml"
require "active_support/core_ext/time"

module Socrates
  module Core
    class StateData
      attr_accessor :state_id, :state_action, :timestamp

      def initialize(state_id: nil, state_action: nil, data: {}, temporary_keys: [])
        @state_id       = state_id
        @state_action   = state_action
        @timestamp      = Time.current
        @data           = data
        @temporary_keys = temporary_keys
      end

      def elapsed_time
        Time.current - @timestamp
      end

      def reset_elapsed_time
        @timestamp = Time.current
      end

      def keys
        @data.keys
      end

      def has_key?(key)
        @data.has_key?(key)
      end

      def has_temporary_key?(key)
        @temporary_keys.include?(key)
      end

      def get(key, clear: false)
        value = @data[key]

        if @temporary_keys.include?(key) || clear
          @temporary_keys.delete(key)
          @data.delete(key)
        end

        value
      end

      def set(key, value)
        @data[key] = value
      end

      def set_temporary(key, value)
        if @data.has_key?(key) && !@temporary_keys.include?(key)
          raise ArgumentError, "Cannot overrite key '#{key}' with a temporary value."
        end

        @data[key] = value
        @temporary_keys << key
      end

      def merge(other)
        @data.merge!(other)
      end

      def clear(key = nil)
        if key
          @data.delete(key)
          @temporary_keys.delete(key)
        else
          @data.clear
          @temporary_keys.clear
        end
      end

      def serialize
        YAML.dump(self)
      end

      def self.deserialize(string)
        YAML.load(string)
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
socrates-0.1.10 lib/socrates/core/state_data.rb
socrates-0.1.9 lib/socrates/core/state_data.rb
socrates-0.1.8 lib/socrates/core/state_data.rb