Class: Stockboy::AttributeMap

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/stockboy/attribute_map.rb

Overview

Table of attributes for finding corresponding field/attribute translations

Instance Method Summary collapse

Constructor Details

#initialize(rows = {}, &block) ⇒ AttributeMap

Initialize a new attribute map



26
27
28
29
30
31
32
# File 'lib/stockboy/attribute_map.rb', line 26

def initialize(rows={}, &block)
  @map = rows
  @unmapped = Hash.new
  if block_given?
    DSL.new(self).instance_eval(&block)
  end
end

Instance Method Details

#[](key) ⇒ Attribute

Retrieve an attribute by symbolic name

Parameters:

  • key (Symbol)

Returns:



39
40
41
# File 'lib/stockboy/attribute_map.rb', line 39

def [](key)
  @map[key]
end

#attribute_from(key) ⇒ Attribute

Fetch the attribute corresponding to the source field name

Parameters:

  • key (String)

Returns:



65
66
67
# File 'lib/stockboy/attribute_map.rb', line 65

def attribute_from(key)
  find { |a| a.from == key } or @unmapped[key] ||= Attribute.new(nil, key, nil)
end

#each(*args) {|| ... } ⇒ Enumerator

Enumerate over attributes

Yield Parameters:

Returns:

  • (Enumerator)


74
75
76
# File 'lib/stockboy/attribute_map.rb', line 74

def each(*args, &block)
  @map.values.each(*args, &block)
end

#insert(key, opts = {}) ⇒ Object

Add or replace a mapped attribute

Parameters:

  • key (Symbol)

    Name of the output attribute

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

Options Hash (opts):

  • from (String)

    Name of input field from reader

  • as (Array, Proc, Translator)

    One or more translators



50
51
52
53
54
55
56
57
58
# File 'lib/stockboy/attribute_map.rb', line 50

def insert(key, opts={})
  to = key.to_sym
  from = opts.fetch(:from, key)
  from = from.to_s.freeze if from.is_a? Symbol
  translators = Array(opts[:as]).map { |t| Translations.translator_for(to, t) }
  ignore_condition = opts[:ignore]
  define_singleton_method(key) { @map[key] }
  @map[key] = Attribute.new(to, from, translators, ignore_condition)
end