Class: Jekyll::Contentful::Importer

Inherits:
Object
  • Object
show all
Defined in:
lib/jekyll-contentful-data-import/importer.rb

Overview

Importer class

Entry fetching logic

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Importer

Returns a new instance of Importer.



12
13
14
# File 'lib/jekyll-contentful-data-import/importer.rb', line 12

def initialize(config)
  @config = config
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



10
11
12
# File 'lib/jekyll-contentful-data-import/importer.rb', line 10

def config
  @config
end

Instance Method Details

#client(space, access_token, options = {}) ⇒ Object



66
67
68
69
70
71
72
73
74
75
# File 'lib/jekyll-contentful-data-import/importer.rb', line 66

def client(space, access_token, options = {})
  options = {
    space: space,
    access_token: access_token,
    dynamic_entries: :auto,
    raise_errors: true
  }.merge(options)

  ::Contentful::Client.new(options)
end

#export_data(name, space_client, options) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/jekyll-contentful-data-import/importer.rb', line 28

def export_data(name, space_client, options)
  Jekyll::Contentful::DataExporter.new(
    name,
    get_entries(space_client, options),
    options
  ).run
end

#get_entries(space_client, options) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/jekyll-contentful-data-import/importer.rb', line 46

def get_entries(space_client, options)
  cda_query = options.fetch('cda_query', {})
  return space_client.entries(cda_query) unless options.fetch('all_entries', false)

  all = []
  query = cda_query.clone
  query[:order] = 'sys.createdAt' unless query.key?(:order)
  num_entries = space_client.entries(limit: 1).total

  page_size = options.fetch('all_entries_page_size', 1000)
  ((num_entries / page_size) + 1).times do |i|
    query[:limit] = page_size
    query[:skip] = i * page_size
    page = space_client.entries(query)
    page.each { |entry| all << entry }
  end

  all
end

#runObject



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/jekyll-contentful-data-import/importer.rb', line 16

def run
  spaces.each do |name, options|
    space_client = client(
      value_for(options, 'space'),
      value_for(options, 'access_token'),
      client_options(options.fetch('client_options', {}))
    )

    export_data(name, space_client, options)
  end
end

#spacesObject



42
43
44
# File 'lib/jekyll-contentful-data-import/importer.rb', line 42

def spaces
  config['spaces'].map(&:first)
end

#value_for(options, key) ⇒ Object



36
37
38
39
40
# File 'lib/jekyll-contentful-data-import/importer.rb', line 36

def value_for(options, key)
  potential_value = options[key]
  return ENV[potential_value.gsub('ENV_', '')] if potential_value.start_with?('ENV_')
  potential_value
end