Class: ETL::Transform::HierarchyLookupTransform

Inherits:
Transform
  • Object
show all
Defined in:
lib/etl/transform/hierarchy_lookup_transform.rb

Overview

Transform which walks up the hierarchy tree to find a value of the current level’s value is nil.

Configuration options:

  • :table: The name of the table to use for lookup (required)

  • :connection: The database adapter connection (required)

  • :parent_id_field: The name of the parent ID field (defaults to :parent_id)

TODO: Let the resolver be implemented in a class so different resolution methods are possible.

Instance Attribute Summary collapse

Attributes inherited from Transform

#configuration, #control, #name

Instance Method Summary collapse

Methods inherited from Transform

benchmarks, transform

Constructor Details

#initialize(control, name, configuration = {}) ⇒ HierarchyLookupTransform

Initialize the transform

Configuration options:

  • :table: The table to search (required)

  • :connection: The ActiveRecord adapter (required)

  • :parent_id_field: The name of the field to use for the parent ID (defaults to :parent_id)



23
24
25
26
# File 'lib/etl/transform/hierarchy_lookup_transform.rb', line 23

def initialize(control, name, configuration={})
  super
  @parent_id_field = configuration[:parent_id_field] || :parent_id
end

Instance Attribute Details

#parent_id_fieldObject

The name of the field to use for the parent ID



15
16
17
# File 'lib/etl/transform/hierarchy_lookup_transform.rb', line 15

def parent_id_field
  @parent_id_field
end

Instance Method Details

#lookup(field, table, parent_id, parent_id_field) ⇒ Object

Lookup the parent value. Note that this method requires that configuration is specified



45
46
47
48
49
50
51
52
53
# File 'lib/etl/transform/hierarchy_lookup_transform.rb', line 45

def lookup(field, table, parent_id, parent_id_field)
  unless configuration.has_key?(:connection)
    raise ETL::ControlError, "The configuration hash must include the database connection"
  end
  
  q = "SELECT #{parent_id_field}, #{field} FROM #{table} WHERE id = #{parent_id}"
  row = configuration[:connection].select_one(q)
  return row[parent_id_field.to_s], row[field.to_s]
end

#transform(name, value, row) ⇒ Object

Transform the value.



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/etl/transform/hierarchy_lookup_transform.rb', line 29

def transform(name, value, row)
  if parent_id = row[parent_id_field]
    # TODO: should use more than just the first source out of the control
    parent_id, value = lookup(name, 
      control.sources.first.configuration[:table], parent_id, parent_id_field)        
    until value || parent_id.nil?
      # TODO: should use more than just the first source out of the control
      parent_id, value = lookup(name, 
        control.sources.first.configuration[:table], parent_id, parent_id_field)
    end
  end
  value
end