Class: PEROBS::DataBase

Inherits:
Object
  • Object
show all
Defined in:
lib/perobs/DataBase.rb

Overview

Base class for all storage back-ends.

Direct Known Subclasses

BTreeDB, DynamoDB

Instance Method Summary collapse

Constructor Details

#initialize(serializer = :json) ⇒ DataBase

Returns a new instance of DataBase.



42
43
44
45
# File 'lib/perobs/DataBase.rb', line 42

def initialize(serializer = :json)
  @serializer = serializer
  @config = {}
end

Instance Method Details

#check_option(name) ⇒ Object

Check a config option and adjust it if needed.

Parameters:

  • name (String)

    Name of the config option.



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/perobs/DataBase.rb', line 88

def check_option(name)
  value = instance_variable_get('@' + name)

  if @config.include?(name)
    # The database already existed and has a setting for this config
    # option. If it does not match the instance variable, adjust the
    # instance variable accordingly.
    unless @config[name] == value
      instance_variable_set('@' + name, @config[name])
    end
  else
    # There is no such config option yet. Create it with the value of the
    # corresponding instance variable.
    @config[name] = value
  end
end

#deserialize(raw) ⇒ Hash

De-serialize the given String into a Ruby object.

Parameters:

  • raw (String)

Returns:

  • (Hash)

    Deserialized version



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/perobs/DataBase.rb', line 69

def deserialize(raw)
  begin
    case @serializer
    when :marshal
      Marshal.load(raw)
    when :json
      JSON.parse(raw, :create_additions => true)
    when :yaml
      YAML.load(raw)
    end
  rescue => e
    raise RuntimeError,
          "Cannot de-serialize object with #{@serializer} parser: " +
          e.message
  end
end

#serialize(obj) ⇒ String

Serialize the given object using the object serializer.

Parameters:

Returns:

  • (String)

    Serialized version



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/perobs/DataBase.rb', line 50

def serialize(obj)
  begin
    case @serializer
    when :marshal
      Marshal.dump(obj)
    when :json
      obj.to_json
    when :yaml
      YAML.dump(obj)
    end
  rescue => e
    raise RuntimeError,
          "Cannot serialize object as #{@serializer}: #{e.message}"
  end
end