Module: Krikri::Mapper

Defined in:
lib/krikri/mapper.rb

Overview

Provides the public interface for defining and running metadata Mappings. Define mappings by passing a block to #define with registered DSL methods; in the simple case pass values to property names:

Krikri::Mapper.define do
  property_name   value
  property_two    another_value do |val|
    transform_value(val)
  end

  nested_resource_property :class => DPLA::MAP::Agent do
    agent_property  agent_value
  end
end

#define accepts :class as an option, to specify the model class to use. The default is DPLA::MAP::Aggregation:

Krikri::Mapper.define :class => MyModelClass {}

Once a Mapping is defined, create mapped records with #map to return objects of the specified class.

See Also:

Defined Under Namespace

Classes: Agent

Constant Summary collapse

Registry =

An application-wide registry of defined mappings

Class.new(Krikri::Registry)

Class Method Summary collapse

Class Method Details

.define(name, opts = {}) { ... } ⇒ Object

Creates mappings and passes DSL methods through to them, then adds them to a global registry.

Parameters:

  • name (Symbol)

    a unique name for the mapper in the registry.

  • opts (Hash) (defaults to: {})

    options to pass to the mapping instance, options are: :class, :parser, and :parser_args

Yields:

  • A block passed through to the mapping instance containing the mapping in the language specified by MappingDSL



40
41
42
43
44
45
46
47
# File 'lib/krikri/mapper.rb', line 40

def define(name, opts = {}, &block)
  klass = opts.fetch(:class, DPLA::MAP::Aggregation)
  parser = opts.fetch(:parser, Krikri::XmlParser)
  parser_args = opts.fetch(:parser_args, nil)
  map = Krikri::Mapping.new(klass, parser, *parser_args)
  map.instance_eval(&block) if block_given?
  Registry.register!(name, map)
end

.map(name, records) ⇒ Array

Maps OriginalRecords to the specified model class using a registered Krikri::Mapping.

Parameters:

  • name (Symbol)

    the name of a registered mapper to use

  • records

    A record or list of records that respond to #to_s

Returns:

  • (Array)

    An array of objects of the model class, with properties set by the mapping.

See Also:



59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/krikri/mapper.rb', line 59

def map(name, records)
  mapping = Registry.get(name)
  records = Array(records) unless records.is_a? Enumerable

  result = records.map do |rec|
    begin
      mapping.process_record(rec)
    rescue => e
      Rails.logger.error(e.message)
      nil
    end
  end
end