Class: Traitorous::Converter::MethodKeyedUniformHash

Inherits:
Object
  • Object
show all
Defined in:
lib/traitorous/converter/method_keyed_uniform_hash.rb

Overview

MethodKeyedUniformedHash is meant to take an array of a simple data

structures and convert each into a uniform class, and then will call a
key_method on that class and use it as the key in the returned hash.

Exported data will be converted into an array calling do_export on each

element

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key_method, uniform_klass) ⇒ MethodKeyedUniformHash

Returns a new instance of MethodKeyedUniformHash.

Parameters:

  • key_method (Symbol)

    the method to call on the uniform_klass instance to generate the key in the returned hash

  • uniform_klass (Class, #new)

    the class to instantiate with each element of the do_import array



15
16
17
18
# File 'lib/traitorous/converter/method_keyed_uniform_hash.rb', line 15

def initialize(key_method, uniform_klass)
  @key_method = key_method
  @uniform_klass = uniform_klass
end

Instance Attribute Details

#key_methodObject

Returns the value of attribute key_method.



10
11
12
# File 'lib/traitorous/converter/method_keyed_uniform_hash.rb', line 10

def key_method
  @key_method
end

#uniform_klassObject

Returns the value of attribute uniform_klass.



10
11
12
# File 'lib/traitorous/converter/method_keyed_uniform_hash.rb', line 10

def uniform_klass
  @uniform_klass
end

Instance Method Details

#do_export(hsh_data) ⇒ Object

Returns Array each element of the values of hsh_data has #export called on it.

Parameters:

  • hsh_data (Hash<obj,#export>)

    keys are ignored

Returns:

  • Array each element of the values of hsh_data has #export called on it.



38
39
40
# File 'lib/traitorous/converter/method_keyed_uniform_hash.rb', line 38

def do_export(hsh_data)
  hsh_data.values.map{|instance| instance.export }
end

#do_import(arr_data) ⇒ Hash

The import instantiates each element of the array as an instance of

the uniform_klass, the key is determined by calling key_method on the
instance and then they are joined to the result hash as a key,
instance pair.

Parameters:

  • arr_data (Array)

    the array of data to instantiate

Returns:

  • (Hash)

    hash containing key, instance pairs



26
27
28
29
30
31
32
33
# File 'lib/traitorous/converter/method_keyed_uniform_hash.rb', line 26

def do_import(arr_data)
  out = {}
  Array(arr_data).each do |elem_data|
    obj = uniform_klass.new(elem_data)
    out[obj.send(key_method)] = obj
  end
  out
end