Class: SupplejackApi::Fragment

Inherits:
Object
  • Object
show all
Includes:
Mongoid::Attributes::Dynamic, Mongoid::Document, Mongoid::Timestamps
Defined in:
app/models/supplejack_api/fragment.rb

Constant Summary collapse

MONGOID_TYPE_NAMES =
{
  string: String,
  integer: Integer,
  datetime: DateTime,
  boolean: Boolean
}.freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.build_mongoid_schemaObject


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'app/models/supplejack_api/fragment.rb', line 32

def self.build_mongoid_schema
  # Build fields
  schema_class.fields.each do |name, field|
    next if field.store == false
    type = field.multi_value.presence ? Array : MONGOID_TYPE_NAMES[field.type]
    self.field name, type: type
  end

  # Build indexes
  if schema_class.mongo_indexes.present?
    schema_class.mongo_indexes.each do |_name, index|
      index_options = !!index.index_options ? index.index_options : {}
      self.index index.fields.first, index_options
    end
  end
end

.schema_classObject

Raises:

  • (NotImplementedError)

28
29
30
# File 'app/models/supplejack_api/fragment.rb', line 28

def self.schema_class
  raise NotImplementedError, 'All subclasses of SupplejackApi::Fragment must define a #schema_class method.'
end

Instance Method Details

#clear_attributesObject


53
54
55
56
57
58
59
# File 'app/models/supplejack_api/fragment.rb', line 53

def clear_attributes
  mutable_fields = self.class.mutable_fields.dup
  mutable_fields.delete('priority') if primary?
  raw_attributes.each do |name, _value|
    self[name] = nil if mutable_fields.key?(name)
  end
end

#primary?Boolean

Returns:

  • (Boolean)

49
50
51
# File 'app/models/supplejack_api/fragment.rb', line 49

def primary?
  priority.zero?
end

#update_from_harvest(attributes = {}) ⇒ Object


61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'app/models/supplejack_api/fragment.rb', line 61

def update_from_harvest(attributes = {})
  attributes = attributes.try(:symbolize_keys) || {}

  self.source_id = Array(attributes[:source_id]).first if attributes[:source_id].present?

  attributes.each do |field, value|
    if self.class.mutable_fields[field.to_s] == Array
      self[field] ||= []
      values = *value
      existing_values = *self[field]
      values = existing_values += values
      send("#{field}=", values.uniq)
    elsif self.class.mutable_fields[field.to_s]
      value = value.first if value.is_a?(Array)
      send("#{field}=", value)
    end
  end

  self.updated_at = Time.now
end