Class: Philiprehberger::DataMapper::Mapping

Inherits:
Object
  • Object
show all
Includes:
Parsable, Reversible
Defined in:
lib/philiprehberger/data_mapper/mapping.rb

Instance Method Summary collapse

Methods included from Reversible

#reverse

Methods included from Parsable

#from_csv, #from_json

Constructor Details

#initialize(&block) ⇒ Mapping

Returns a new instance of Mapping.



12
13
14
15
16
# File 'lib/philiprehberger/data_mapper/mapping.rb', line 12

def initialize(&block)
  @fields = []
  @computed_fields = []
  instance_eval(&block) if block
end

Instance Method Details

#array_field(target, split: ',', **opts, &transform) ⇒ Object



26
27
28
# File 'lib/philiprehberger/data_mapper/mapping.rb', line 26

def array_field(target, split: ',', **opts, &transform)
  field(target, split: split, **opts, &transform)
end

#computed(target) ⇒ Object



22
23
24
# File 'lib/philiprehberger/data_mapper/mapping.rb', line 22

def computed(target, &)
  @computed_fields << ComputedDefinition.new(target, &)
end

#field(target) ⇒ Object



18
19
20
# File 'lib/philiprehberger/data_mapper/mapping.rb', line 18

def field(target, ...)
  @fields << FieldDefinition.new(target, ...)
end

#field_namesArray<Symbol>

Names (targets) of every declared field, including computed fields.

Returns:

  • (Array<Symbol>)


50
51
52
# File 'lib/philiprehberger/data_mapper/mapping.rb', line 50

def field_names
  @fields.map(&:target) + @computed_fields.map(&:target)
end

#map(hash) ⇒ Object



30
31
32
33
34
# File 'lib/philiprehberger/data_mapper/mapping.rb', line 30

def map(hash)
  result = map_fields(hash)
  apply_computed(hash, result)
  result
end

#map_all(array) ⇒ Object



43
44
45
# File 'lib/philiprehberger/data_mapper/mapping.rb', line 43

def map_all(array)
  array.map { |hash| map(hash) }
end

#map_with_validation(hash) ⇒ Object



36
37
38
39
40
41
# File 'lib/philiprehberger/data_mapper/mapping.rb', line 36

def map_with_validation(hash)
  result = {}
  errors = collect_errors(hash, result)
  apply_computed(hash, result)
  MappingResult.new(result, errors)
end