Class: JsonMapping

Inherits:
Object
  • Object
show all
Defined in:
lib/json_mapping.rb

Overview

Stores and applies a mapping to an input ruby Hash

Defined Under Namespace

Classes: FormatError, PathError, TransformError

Instance Method Summary collapse

Constructor Details

#initialize(schema_path, transforms = {}) ⇒ JsonMapping

Returns a new instance of JsonMapping.

Parameters:

  • schema_path (String)

    The path to the YAML schema

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

    A hash of callable objects (Procs/Lambdas). Keys must match transform names specified in YAML



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/json_mapping.rb', line 21

def initialize(schema_path, transforms = {})
  schema = YAML.safe_load(File.read(schema_path))

  @conditions = (schema['conditions'] || {}).map do |key, value|
    [key, Object.const_get("Conditions::#{value['class']}").new(value['predicate'])]
  end.to_h

  @object_schemas = schema['objects']
  @transforms = transforms || {}
  @logger = Logger.new($stdout)
end

Instance Method Details

#apply(input_hash) ⇒ Array

Returns An array of output hashes representing the mapped objects.

Parameters:

  • input_hash (Hash)

    A ruby hash onto which the schema should be applied

Returns:

  • (Array)

    An array of output hashes representing the mapped objects

Raises:



36
37
38
39
40
# File 'lib/json_mapping.rb', line 36

def apply(input_hash)
  raise FormatError, 'Must define objects under the \'objects\' name' if @object_schemas.nil?

  @object_schemas.map { |schema| parse_object(input_hash, schema) }.reduce(&:merge)
end