class Contentful::Converter::ContentfulModelToJson

Constants

FIELD_TYPE

Attributes

config[R]
logger[R]

Public Class Methods

new(settings) click to toggle source
# File lib/converters/contentful_model_to_json.rb, line 11
def initialize(settings)
  @config = settings
  @logger = Logger.new(STDOUT)
end

Public Instance Methods

content_type_name(content_type) click to toggle source
# File lib/converters/contentful_model_to_json.rb, line 68
def content_type_name(content_type)
  I18n.transliterate(content_type).underscore.tr(' ', '_')
end
convert_to_import_form() click to toggle source
# File lib/converters/contentful_model_to_json.rb, line 26
def convert_to_import_form
  logger.info 'Converting Contentful model to Contentful import structure...'
  File.open(config.converted_model_dir, 'w') { |file| file.write({}) }
  content_type_file = JSON.parse(File.read(config.content_types))['items']
  content_type_file.each do |content_type|
    parsed_content_type = {
        id: content_type['sys']['id'],
        name: content_type['name'],
        description: content_type['description'],
        displayField: content_type['displayField'],
        fields: create_content_type_fields(content_type)
    }
    import_form = JSON.parse(File.read(config.converted_model_dir))
    File.open(config.converted_model_dir, 'w') do |file|
      file.write(JSON.pretty_generate(import_form.merge!(content_type['name'] => parsed_content_type)))
    end
  end
  logger.info "Done! Contentful import structure file saved in #{config.converted_model_dir}"
end
create_content_type_fields(content_type) click to toggle source
# File lib/converters/contentful_model_to_json.rb, line 46
def create_content_type_fields(content_type)
  content_type['fields'].each_with_object({}) do |(field, _value), results|
    id = link_id(field)
    results[id] = case field['type']
                    when 'Link'
                      {id: field['id'], type: field['linkType'], link: 'Link'}
                    when 'Array'
                      {id: field['id'], type: field['type'], link_type: field['items']['linkType'], link: field['items']['type']}
                    else
                      field['type']
                  end
  end
end
create_content_type_json() click to toggle source
# File lib/converters/contentful_model_to_json.rb, line 16
def create_content_type_json
  logger.info 'Create JSON files with content types structure...'
  config.contentful_structure.each do |content_type, values|
    content_type_name = content_type_name(content_type)
    create_directory(config.collections_dir)
    ContentTypesStructureCreator.new(config).create_content_type_json_file(content_type_name, values)
  end
  logger.info 'Done!'
end
create_directory(path) click to toggle source
# File lib/converters/contentful_model_to_json.rb, line 72
def create_directory(path)
  FileUtils.mkdir_p(path) unless File.directory?(path)
end