Sha256: 76ef6faab06d0f576e12c2f98216bc3ed0034eb87994950c0a9414dd81b5580e

Contents?: true

Size: 1.22 KB

Versions: 2

Compression:

Stored size: 1.22 KB

Contents

require 'yaml'

module CouchbaseModelLogging

  class Logger

    attr_accessor :client, :prefix, :separator

    def initialize(client, prefix = nil, options = { })
      self.client    = client
      self.prefix    = prefix
      self.separator = options[:separator] || '[SEP]'
    end

    def key?(key)
      !get(key).nil?
    end

    def encode(hash)
      yaml = hash.to_yaml
      raise CouchbaseModelLogging::ReplacementError, "Found separator [#{separator}] in YAML string" if yaml.index(separator)
      yaml + separator
    end

    def add(key, hash = { })
      yaml     = encode hash
      pref_key = prefixed_key_for key
      begin
        client.append pref_key, yaml, :format => :plain
      rescue ::Couchbase::Error::NotStored
        client.add pref_key, yaml, :format => :plain
      end
    end

    def get(key)
      client.get(prefixed_key_for(key), :format => :plain)
    end

    def decode(str)
      return [] if str.nil? || str.empty?
      str.split(separator).map { |yaml| YAML.load yaml }
    end

    def all(key)
      decode get(key)
    end

    def delete(key)
      client.delete prefixed_key_for(key)
    end

    def prefixed_key_for(key)
      prefix.nil? ? key.to_s : "#{prefix}::#{key}"
    end

  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
couchbase_model_logging-0.0.4 lib/couchbase_model_logging/logger.rb
couchbase_model_logging-0.0.3 lib/couchbase_model_logging/logger.rb