Class: CSVConverter::Converters::HashConverter

Inherits:
BaseConverter show all
Defined in:
lib/csv_converter/converters/hash_converter.rb

Overview

Converts a string with key pair values into ruby hashes

Instance Attribute Summary

Attributes inherited from BaseConverter

#options, #raw_data

Instance Method Summary collapse

Methods inherited from BaseConverter

#data, #empty_value?

Constructor Details

#initialize(raw_data, options = {}) ⇒ HashConverter

A new instance of HashConverter.

Parameters:

  • raw_data (String)

    the raw data of the attribute being processed.

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

    the options for the converter provided in the mappings. Additionally, contains the details of the data being processed. See BaseConverter#option. The item_separator key is required. If item_separator is nil then an error is raised. The key_value_separator key is required. If key_value_separator is nil then an error is raised.



13
14
15
16
17
# File 'lib/csv_converter/converters/hash_converter.rb', line 13

def initialize(raw_data, options = {})
  super(raw_data, options)

  validate_options
end

Instance Method Details

#callHash

Converts data into a hash by splitting the string on the item_separator to get the items and then by spliting the items on key_value_separator to get the key/value.

Returns:

  • (Hash)

    if an error occurs during conversion an empty hash is returned.



22
23
24
25
26
# File 'lib/csv_converter/converters/hash_converter.rb', line 22

def call
  call!
rescue CSVConverter::Error
  nullable_object
end

#call!Hash

Converts data into a hash by splitting the string on the item_separator to get the items and then by spliting the items on key_value_separator to get the key/value.

Returns:

  • (Hash)

    if an error occurs during conversion an error is raised.



31
32
33
34
35
36
37
# File 'lib/csv_converter/converters/hash_converter.rb', line 31

def call!
  data.split(options[:item_separator]).map do |items|
    items.split(options[:key_value_separator]).map(&:strip)
  end.to_h
rescue StandardError => e
  raise CSVConverter::Error.new(e.message, options)
end