Class: Newman::Store

Inherits:
Object
  • Object
show all
Defined in:
lib/newman/store.rb

Instance Method Summary collapse

Constructor Details

#initialize(filename) ⇒ Store

To initialize a ‘Newman::Store` object, a `filename` string must be provided, i.e.

store = Newman::Store.new("simple.store")

This filename will be used to initialize a ‘PStore` object after first running `FileUtils.mkdir_p` to create any directories within the path to the filename if they do not already exist. Once that `PStore` object is created, two root keys will be mapped to empty Hash objects if they are not set already: `:indentifers` and `:columns`.

While it’s okay to treat the ‘PStore` object as an implementation detail, we will treat our interactions with it as part of Newman’s **external interface**, so that we are more conservative about making backwards incompatible changes to the databases created by ‘Newman::Store`.



32
33
34
35
36
37
38
39
40
41
# File 'lib/newman/store.rb', line 32

def initialize(filename)
  FileUtils.mkdir_p(File.dirname(filename))

  self.data = PStore.new(filename)

  write do
    data[:identifiers] ||= {} 
    data[:columns]     ||= {}
  end
end

Instance Method Details

#[](column_key) ⇒ Object

‘Newman::Store#[]` is syntactic sugar for initializing a `Newman::Recorder` object, and is meant to be used for accessing and manipulating column data by `column_key`, i.e.

store[:subscriptions].create("[email protected]")

This method is functionally equivalent to the following code:

recorder = Newman::Recorder.new(:subscriptions, store)
recorder.create("[email protected]")

For aesthetic reasons and for forward compatibility, it is preferable to use ‘Newman::Store#[]` rather than instantiating a `Newman::Recorder` object directly.



60
61
62
# File 'lib/newman/store.rb', line 60

def [](column_key)
  Recorder.new(column_key, self) 
end

#readObject

‘Newman::Store#read` initiates a read only transaction and then yields the underlying `PStore` object stored in the `data` field.



69
70
71
# File 'lib/newman/store.rb', line 69

def read
  data.transaction(:read_only) { yield(data) }
end

#writeObject

‘Newman::Store#read` initiates a read/write transaction and then yields the underlying `PStore` object stored in the `data` field.



78
79
80
# File 'lib/newman/store.rb', line 78

def write
  data.transaction { yield(data) }
end