Module: SupplejackApi::Support::Harvestable

Extended by:
ActiveSupport::Concern
Included in:
PreviewRecord, Record
Defined in:
app/models/supplejack_api/support/harvestable.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#clear_attributesObject

Sets all the Record attributes to nil except the internal ones that shouldn’t be removed (_id, _type, etc..)



55
56
57
58
# File 'app/models/supplejack_api/support/harvestable.rb', line 55

def clear_attributes
  self[:source_url] = nil
  primary_fragment.clear_attributes
end

#create_or_update_fragment(attributes) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
# File 'app/models/supplejack_api/support/harvestable.rb', line 14

def create_or_update_fragment(attributes)
  if fragment = find_fragment(attributes['source_id'])
    fragment.clear_attributes
  elsif fragments.count.zero?
    fragment = primary_fragment
  else
    fragment = fragments.build
  end

  fragment.update_from_harvest(attributes)
end

#set_status(required_fragments) ⇒ Object



47
48
49
50
# File 'app/models/supplejack_api/support/harvestable.rb', line 47

def set_status(required_fragments)
  missing_fragments = Array(required_fragments) - fragments.map(&:source_id)
  self.status = missing_fragments.empty? ? 'active' : 'partial'
end

#unset_null_fieldsObject



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'app/models/supplejack_api/support/harvestable.rb', line 60

def unset_null_fields
  raw_json = raw_attributes || {}
  unset_hash = {}
  raw_json.each do |key, value|
    unset_hash.merge!(key => true) if value.nil?
  end
  if raw_json['fragments'].present?
    raw_json['fragments'].each_with_index do |fragment, index|
      next if fragment.nil?
      fragment.each do |key, value|
        unset_hash.merge!("fragments.#{index}.#{key}" => true) if value.nil?
      end
    end
  end
  collection.find(atomic_selector).update('$unset' => unset_hash) if unset_hash.any?
end

#update_from_harvest(attributes = {}) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'app/models/supplejack_api/support/harvestable.rb', line 26

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

  attributes[:status] ||= 'active'

  self.class.fields.each do |name, _field|
    if attributes.key?(name.to_sym)
      value = Array(attributes[name.to_sym]).first
      send("#{name}=", value)
    end
  end

  primary_fragment.update_from_harvest(attributes)
  self.updated_at = Time.now
end

#update_from_harvest!(attributes = {}) ⇒ Object



42
43
44
45
# File 'app/models/supplejack_api/support/harvestable.rb', line 42

def update_from_harvest!(attributes = {})
  update_from_harvest(attributes)
  save
end