Class: Palsy::Object

Inherits:
Generic show all
Defined in:
lib/palsy/basic/object.rb

Overview

Basic “symbol table”-ish object.

The difference between using this over Palsy::Map is that objects take a full database table, treat all indexes as strings, and do not act like Palsy::Collection subclasses.

Example:

obj = Palsy::Object.new("object_table")
obj["var1"] = 1
obj["var2"] = 2
obj["var1"] == 1 #=> true

This will create a table in the database named “object_table” and all i/o against this object (unless specified otherwise on a per-method basis) will go through it.

Note that while all object keys are treated as strings, values are marshalled and must be capable of doing so.

Instance Attribute Summary

Attributes inherited from Generic

#db, #object_name, #table_name

Instance Method Summary collapse

Methods inherited from Generic

#==, #_dump, _load, #initialize, #post_marshal_init

Constructor Details

This class inherits a constructor from Palsy::Generic

Instance Method Details

#[](key) ⇒ Object

Get an object by referencing its key. Returns nil unless it exists.



29
30
31
32
33
34
35
36
37
38
# File 'lib/palsy/basic/object.rb', line 29

def [](key)
  value = begin
            ret = @db.execute_t("select value from #{@table_name} where key=?", [key])
            (ret && ret.first) ? ret.first.first : nil
          rescue SQLite3::Exception
            nil
          end

  return value && Marshal.load(value)
end

#[]=(key, value) ⇒ Object

Set an object. Returns the object. The object must be able to be Marshalled.



43
44
45
46
47
48
49
# File 'lib/palsy/basic/object.rb', line 43

def []=(key, value)
  @db.with_t do
    delete(key)
    @db.execute_t("insert into #{@table_name} (key, value) values (?, ?)", [key, Marshal.dump(value)])
  end
  value
end

#create_tableObject

Defines the schema for this data type.



61
62
63
64
65
66
67
68
69
70
# File 'lib/palsy/basic/object.rb', line 61

def create_table
  @db.execute_t <<-EOF
    create table if not exists #{@table_name} (
      id integer not null primary key autoincrement,
      key varchar(255) not null,
      value text not null,
      UNIQUE(key)
    )
  EOF
end

#delete(key) ⇒ Object

Deletes an object.



54
55
56
# File 'lib/palsy/basic/object.rb', line 54

def delete(key)
  @db.execute_t("delete from #{@table_name} where key=?", [key])
end