Module: Volt::Models::Helpers::Base

Included in:
ArrayModel, Volt::Model
Defined in:
lib/volt/models/helpers/base.rb

Overview

A place for things shared between an ArrayModel and a Model

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

ID_CHARS =
[('a'..'f'), ('0'..'9')].map(&:to_a).flatten

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



122
123
124
# File 'lib/volt/models/helpers/base.rb', line 122

def self.included(base)
  base.send :extend, ClassMethods
end

Instance Method Details

#deep_unwrap(value) ⇒ Object



6
7
8
9
10
11
12
13
14
# File 'lib/volt/models/helpers/base.rb', line 6

def deep_unwrap(value)
  if value.is_a?(Model)
    value.to_h
  elsif value.is_a?(ArrayModel)
    value.to_a
  else
    value
  end
end

#event_added(event, first, first_for_event) ⇒ Object

Pass to the persisotr



17
18
19
# File 'lib/volt/models/helpers/base.rb', line 17

def event_added(event, first, first_for_event)
  @persistor.event_added(event, first, first_for_event) if @persistor
end

#event_removed(event, last, last_for_event) ⇒ Object

Pass to the persistor



22
23
24
# File 'lib/volt/models/helpers/base.rb', line 22

def event_removed(event, last, last_for_event)
  @persistor.event_removed(event, last, last_for_event) if @persistor
end

#generate_idObject

Create a random unique id that can be used as the mongo id as well



29
30
31
32
33
34
# File 'lib/volt/models/helpers/base.rb', line 29

def generate_id
  id = []
  24.times { id << ID_CHARS.sample }

  id.join
end

#rootObject

returns the root model for the collection the model is currently on. So if the model is persisted somewhere on store, it will return “‘store“`



69
70
71
# File 'lib/volt/models/helpers/base.rb', line 69

def root
  persistor.try(:root_model)
end

#self_attributesObject

Return the attributes that are only for this model and any hash sub models but not any sub-associations.



39
40
41
42
43
44
45
46
47
48
# File 'lib/volt/models/helpers/base.rb', line 39

def self_attributes
  # Don't store any sub-models, those will do their own saving.
  attributes.reject { |k, v| v.is_a?(ArrayModel) }.map do |k,v|
    if v.is_a?(Model)
      v = v.self_attributes
    end

    [k,v]
  end.to_h
end

#setup_persistor(persistor) ⇒ Object

Takes the persistor if there is one and



52
53
54
55
56
57
58
59
60
61
# File 'lib/volt/models/helpers/base.rb', line 52

def setup_persistor(persistor)
  # Use page as the default persistor
  persistor ||= Persistors::Page
  if persistor.respond_to?(:new)
    @persistor = persistor.new(self)
  else
    # an already initialized persistor was passed in
    @persistor = persistor
  end
end

#storeObject



63
64
65
# File 'lib/volt/models/helpers/base.rb', line 63

def store
  Volt.current_app.store
end