Module: Lich::Common::Vars

Defined in:
documented/vars.rb,
documented/common/vars.rb

Constant Summary collapse

@@vars =
Hash.new
@@md5 =
nil
@@load_state =
LoadState::UNLOADED
@@load =

Proc that loads variables from database on first access

proc {
  Lich.db_mutex.synchronize {
    if @@load_state == LoadState::UNLOADED
      @@load_state = LoadState::LOADING
      begin
        h = Lich.db.get_first_value(
          'SELECT hash FROM uservars WHERE scope=?;',
          ["#{XMLData.game}:#{XMLData.name}".encode('UTF-8')]
        )
      rescue SQLite3::BusyException
        sleep 0.1
        retry
      end
       if h
        begin
          hash = Marshal.load(h)
          # Normalize all keys to strings during load
          hash.each { |k, v| @@vars[normalize_key(k)] = v }
          @@md5 = Digest::MD5.hexdigest(hash.to_s)
        rescue StandardError => e
          respond "--- Lich: error: #{e}"
          respond e.backtrace[0..2]
        end
      end
      @@load_state = LoadState::LOADED
    end
  }
  nil
}
@@save =

Proc that saves variables to database if modified

proc {
  Lich.db_mutex.synchronize {
    if @@load_state == LoadState::LOADED
      current_md5 = Digest::MD5.hexdigest(@@vars.to_s)
      if current_md5 != @@md5
        @@md5 = current_md5
        blob = SQLite3::Blob.new(Marshal.dump(@@vars))
        begin
          Lich.db.execute(
            'INSERT OR REPLACE INTO uservars(scope,hash) VALUES(?,?);',
            ["#{XMLData.game}:#{XMLData.name}".encode('UTF-8'), blob]
          )
        rescue SQLite3::BusyException
          sleep 0.1
          retry
        end
      end
    end
  }
  nil
}

Class Method Summary collapse

Class Method Details

.normalize_key(key) ⇒ String

Normalizes the given key to a string.

Parameters:

  • key (Object)

    the key to normalize

Returns:

  • (String)

    the normalized key as a string



19
20
21
# File 'documented/common/vars.rb', line 19

def self.normalize_key(key)
  key.to_s
end