class Decidim::Admin::Import::Creator

This is an abstract class with a very naive default implementation for the importers to use. It can also serve as a superclass of your own implementation.

It is used to be run against each element of an importable collection in order to parse relevant fields. Every import should specify their own creator or this default will be used.

Attributes

data[R]

Public Class Methods

new(data, context = nil) click to toggle source

Initializes the creator with a resource.

data - The data hash to parse. context - The context needed by the producer

# File lib/decidim/admin/import/creator.rb, line 20
def initialize(data, context = nil)
  @data = data.except(:id, "id")
  @context = context
end
resource_klass() click to toggle source

Retuns the resource class to be created with the provided data.

# File lib/decidim/admin/import/creator.rb, line 26
def self.resource_klass
  raise NotImplementedError, "#{self.class.name} does not define resource class"
end

Public Instance Methods

finish!() click to toggle source
# File lib/decidim/admin/import/creator.rb, line 49
def finish!
  resource.save!
end
produce() click to toggle source

Public: Returns a created object with the parsed data.

Returns a target object.

# File lib/decidim/admin/import/creator.rb, line 45
def produce
  self.class.resource_klass.new(resource_attributes)
end
resource_attributes() click to toggle source

Can be used to convert the data hash to the resource attributes in case the data hash to be imported has different column names than the resource object to be created of it.

By default returns the data hash but can be implemented by each creator implementation.

Returns the resource attributes to be passed for the constructor.

# File lib/decidim/admin/import/creator.rb, line 38
def resource_attributes
  @data
end

Private Instance Methods

locale_hasher(field, locales) click to toggle source

Collect field's language specified cells to one hash

field - The field name eg. “title” locales - Available locales

Returns the hash including locale-imported_data pairs. eg. {en: “Heading”, ca: “Cap”, es: “Bóveda”}

# File lib/decidim/admin/import/creator.rb, line 67
def locale_hasher(field, locales)
  return data[field.to_sym] if data.has_key?(field.to_sym)

  hash = {}
  locales.each do |locale|
    parsed = data[:"#{field}/#{locale}"]
    next if parsed.nil?

    hash[locale] = parsed
  end
  hash
end
resource() click to toggle source
# File lib/decidim/admin/import/creator.rb, line 55
def resource
  raise NotImplementedError, "#{self.class.name} does not define resource"
end