class DataMaps::Mapping
The mapping class which defines a mapping
@since 0.0.1 attr_reader [Hash] mapping the compiled mapping attr_reader [Hash] mapping_hash
the mapping description
Attributes
Public Class Methods
Initializer for the Mapping
class
@param [Hash] mapping_hash
@raise [ArgumentError] when the given mapping_hash
is not a Hash
# File lib/data_maps/mapping.rb, line 18 def initialize(mapping_hash = {}) raise ArgumentError.new('The mapping_hash must be a Hash') unless mapping_hash.is_a? Hash @mapping = {} @mapping_hash = mapping_hash.with_indifferent_access end
Public Instance Methods
Compile the mapping statements, this will lazily called on first use
# File lib/data_maps/mapping.rb, line 27 def compile unless @_compiled # iterate over the mapping_hash and initialize mapping for each key mapping_hash.each do |destination, map| @mapping[destination] = _create_statement(destination, map) end @_compiled = true end end
Allow iterations over all statements
@param [Block] &block the block to execute for each map statement @return [Enumerator|self] return the enumerator if no block given or self
# File lib/data_maps/mapping.rb, line 63 def each_statement compile return enum_for(:each_statement) unless block_given? # return Enumerator mapping.each do |destination, statement| yield destination, statement end self end
Execute mapping on the given data
@param [Hash] data @return [Hash] the mapped data
# File lib/data_maps/mapping.rb, line 79 def execute(data) result = {} each_statement do |destination, statement| key, value = statement.execute(data) result[key] = value unless value.is_a? DataMaps::FilteredValue end result end
Getter to get the statement for a destination_field
@param [String|Symbol] destination the field name to receive statement for @raise [KeyError] when the destination_field isn’t present in map
# File lib/data_maps/mapping.rb, line 51 def get_statement_for(destination) compile raise KeyError.new("The map has no statement for field: #{destination}") unless mapping.has_key?(destination) mapping[destination] end
Validate the mapping statements, this is a compiling without save the compiled mapping
# File lib/data_maps/mapping.rb, line 39 def valid? true if validate rescue false end
# File lib/data_maps/mapping.rb, line 43 def validate mapping_hash.each &method(:_create_statement) end
Protected Instance Methods
Create a mapping statement
@protected
@param [String] destination The destination field @param [String|Hash] mapping
@return [Statement] executable statement
# File lib/data_maps/mapping.rb, line 99 def _create_statement(destination, mapping) mapping = { from: mapping } if mapping.is_a? String mapping[:to] = destination DataMaps::Statement.create_from_map(mapping) end