Module: ConstructorIORails::ClassMethods

Defined in:
lib/constructorio-rails.rb

Instance Method Summary collapse

Instance Method Details

#constructorio_autocomplete(fields, autocomplete_key = ConstructorIORails.configuration.autocomplete_key, autocomplete_section = ConstructorIORails.configuration.autocomplete_section) ⇒ Object

“fields” is expected to be an array of strings or an array of hashes, like: “product_name”, “description”

  • or -

{ ‘attribute’ => ‘product_name’, ‘metadata’ => { metadata_one => ->{ something_dynamic }} }

Raises:



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/constructorio-rails.rb', line 43

def constructorio_autocomplete(fields,
                               autocomplete_key = ConstructorIORails.configuration.autocomplete_key,
                               autocomplete_section = ConstructorIORails.configuration.autocomplete_section)
  # All fields require an attribute
  field_names = fields.map { |f| f.is_a?(String) ? f : f['attribute'] }
  raise MissingItemName if field_names.include? nil

  field_names.each do |field|
    ConstructorIORails::Fields.instance.add(self.model_name, field)
  end

  # transform the data
  transformed = {}
  fields.each do |field|
    if field.is_a?(String)
      transformed[field] = {}
    else
      transformed[field['attribute']] = field['metadata']
    end
  end

  after_save do |record|
    updated_fields = record.changed.select { |c| field_names.include? c }
    updated_fields.each do |field|
      record.send(:constructorio_add_record, record[field.to_sym], transformed[field], autocomplete_key, autocomplete_section)
    end
  end

  before_destroy do |record|
    field_names.each do |field|
      record.send(:constructorio_delete_record, record[field.to_sym], transformed[field], autocomplete_key, autocomplete_section)
    end
  end
end