Module: Volt::ModelHelpers

Included in:
ArrayModel, Model
Defined in:
lib/volt/models/model_helpers/model_helpers.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



95
96
97
# File 'lib/volt/models/model_helpers/model_helpers.rb', line 95

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

Instance Method Details

#deep_unwrap(value) ⇒ Object



4
5
6
7
8
9
10
11
12
# File 'lib/volt/models/model_helpers/model_helpers.rb', line 4

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



15
16
17
# File 'lib/volt/models/model_helpers/model_helpers.rb', line 15

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



20
21
22
# File 'lib/volt/models/model_helpers/model_helpers.rb', line 20

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



27
28
29
30
31
32
# File 'lib/volt/models/model_helpers/model_helpers.rb', line 27

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

  id.join
end

#self_attributesObject

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



37
38
39
40
41
42
43
44
45
46
# File 'lib/volt/models/model_helpers/model_helpers.rb', line 37

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



50
51
52
53
54
55
56
57
58
59
# File 'lib/volt/models/model_helpers/model_helpers.rb', line 50

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