Class: Volt::Persistors::LocalStore

Inherits:
Base show all
Defined in:
lib/volt/models/persistors/local_store.rb

Overview

Backs a collection in the local store

Instance Method Summary collapse

Methods inherited from Base

#event_added, #event_removed, #removed

Constructor Details

#initialize(model) ⇒ LocalStore

Returns a new instance of LocalStore.



9
10
11
# File 'lib/volt/models/persistors/local_store.rb', line 9

def initialize(model)
  @model = model
end

Instance Method Details

#added(model, index) ⇒ Object

Called when a model is added to the collection



30
31
32
# File 'lib/volt/models/persistors/local_store.rb', line 30

def added(model, index)
  root_model.persistor.save_all
end

#changed(attribute_name) ⇒ Object

Callled when an item is changed (or removed)



52
53
54
# File 'lib/volt/models/persistors/local_store.rb', line 52

def changed(attribute_name)
  root_model.persistor.save_all
end

#loaded(initial_state = nil) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/volt/models/persistors/local_store.rb', line 34

def loaded(initial_state = nil)
  # When the main model is first loaded, we pull in the data from the
  # store if it exists
  if @model.path == []
    json_data = LocalStorage['volt-store']
    if json_data
      root_attributes = JSON.parse(json_data)

      @loading_data = true
      root_attributes.each_pair do |key, value|
        @model.send(:"_#{key}=", value)
      end
      @loading_data = nil
    end
  end
end

#root_modelObject

Find the root for this model



14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/volt/models/persistors/local_store.rb', line 14

def root_model
  node = @model

  loop do
    parent = node.parent
    if parent
      node = parent
    else
      break
    end
  end

  node
end

#save_allObject

Called on the root



57
58
59
60
61
62
63
# File 'lib/volt/models/persistors/local_store.rb', line 57

def save_all
  return if @loading_data

  json_data = JSON.dump(@model.to_h)

  LocalStorage['volt-store'] = json_data
end