Class: HistoryBook::Sequel::Store
- Inherits:
-
Object
- Object
- HistoryBook::Sequel::Store
- Defined in:
- lib/history_book/sequel/store.rb
Instance Method Summary collapse
- #_create_events_table ⇒ Object
- #_decode_data(data) ⇒ Object
- #_encode_data(data) ⇒ Object
- #_load_rows(id, from, to) ⇒ Object
- #_max_revision(id) ⇒ Object
- #_transform_row(row) ⇒ Object
-
#initialize(db) ⇒ Store
constructor
A new instance of Store.
- #load_events(id, options = {}) ⇒ Object
- #store_events(id, new_events) ⇒ Object
Constructor Details
#initialize(db) ⇒ Store
Returns a new instance of Store.
4 5 6 7 8 |
# File 'lib/history_book/sequel/store.rb', line 4 def initialize(db) @db = db _create_events_table end |
Instance Method Details
#_create_events_table ⇒ Object
38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/history_book/sequel/store.rb', line 38 def _create_events_table @db.create_table?(:events) do primary_key :id String :stream_id Integer :revision DateTime :timestamp String :type File :data index [:stream_id, :revision], :unique => true end end |
#_decode_data(data) ⇒ Object
71 72 73 |
# File 'lib/history_book/sequel/store.rb', line 71 def _decode_data(data) MultiJson.decode(data).with_indifferent_access end |
#_encode_data(data) ⇒ Object
67 68 69 |
# File 'lib/history_book/sequel/store.rb', line 67 def _encode_data(data) MultiJson.encode(data.to_hash).to_sequel_blob end |
#_load_rows(id, from, to) ⇒ Object
50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/history_book/sequel/store.rb', line 50 def _load_rows(id, from, to) rows = @db. from(:events). where(:stream_id => id). where('revision >= ?', from) if to rows = rows.where('revision <= ?', to) end rows end |
#_max_revision(id) ⇒ Object
63 64 65 |
# File 'lib/history_book/sequel/store.rb', line 63 def _max_revision(id) @db.from(:events).where(:stream_id => id).max(:revision) || 0 end |
#_transform_row(row) ⇒ Object
75 76 77 78 79 |
# File 'lib/history_book/sequel/store.rb', line 75 def _transform_row(row) type = row[:type].to_sym data = _decode_data(row[:data]) HistoryBook::Event.new(type, data) end |
#load_events(id, options = {}) ⇒ Object
10 11 12 13 14 15 16 17 18 |
# File 'lib/history_book/sequel/store.rb', line 10 def load_events(id, = {}) = {:from => 1, :to => nil}.merge() from, to = .values_at(:from, :to) rows = _load_rows(id, from, to) rows.map do |row| _transform_row(row) end end |
#store_events(id, new_events) ⇒ Object
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/history_book/sequel/store.rb', line 20 def store_events(id, new_events) @db.transaction do max_revision = _max_revision(id) new_events = Array(new_events) new_events.each do |new_event| max_revision += 1 @db[:events].insert( :stream_id => id, :revision => max_revision, :timestamp => DateTime.now.utc, :type => new_event.type.to_s, :data => _encode_data(new_event.data) ) end end end |