Class: ComfortableMexicanSofa::Seeds::Snippet::Importer

Inherits:
Importer
  • Object
show all
Defined in:
lib/comfortable_mexican_sofa/seeds/snippet/importer.rb

Instance Attribute Summary

Attributes inherited from Importer

#from, #path, #seed_ids, #site, #to

Instance Method Summary collapse

Constructor Details

#initialize(from, to = from) ⇒ Importer

Returns a new instance of Importer.



6
7
8
9
# File 'lib/comfortable_mexican_sofa/seeds/snippet/importer.rb', line 6

def initialize(from, to = from)
  super
  self.path = ::File.join(ComfortableMexicanSofa.config.seeds_path, from, "snippets/")
end

Instance Method Details

#import!Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/comfortable_mexican_sofa/seeds/snippet/importer.rb', line 11

def import!
  Dir.glob("#{path}/*.html").each do |path|
    identifier = File.basename(path, ".html")

    # reading file content in, resulting in a hash
    content_hash = parse_file_content(path)

    # parsing attributes section
    attributes_yaml = content_hash.delete("attributes")
    attrs           = YAML.safe_load(attributes_yaml)

    snippet = site.snippets.where(identifier: identifier).first_or_initialize

    if fresh_seed?(snippet, path)
      category_ids = category_names_to_ids(snippet, attrs.delete("categories"))

      snippet.attributes = attrs.merge(
        category_ids: category_ids,
        content:      content_hash["content"]
      )

      if snippet.save
        message = "[CMS SEEDS] Imported Snippet \t #{snippet.identifier}"
        ComfortableMexicanSofa.logger.info(message)
      else
        message = "[CMS SEEDS] Failed to import Snippet \n#{snippet.errors.inspect}"
        ComfortableMexicanSofa.logger.warn(message)
      end
    end

    # Tracking what page from seeds we're working with. So we can remove pages
    # that are no longer in seeds
    seed_ids << snippet.id
  end

  # cleaning up
  site.snippets.where("id NOT IN (?)", seed_ids).destroy_all
end