Module: SequelDM::Mapper::ClassMethods

Defined in:
lib/sequel_dm/mapper.rb

Instance Method Summary collapse

Instance Method Details

#map(entity_class, &mappings_proc) ⇒ Object



12
13
14
15
16
# File 'lib/sequel_dm/mapper.rb', line 12

def map(entity_class, &mappings_proc)
  SequelDM::ArgsValidator.is_class!(entity_class, :entity_class)
  self.entity_class = entity_class
  self.mappings     = SequelDM::MappingsDSL.new(&mappings_proc).mappings
end

#to_entity(hash) ⇒ Object



18
19
20
21
22
23
24
25
26
27
# File 'lib/sequel_dm/mapper.rb', line 18

def to_entity(hash)
  attributes = {}
  entity = self.entity_class.new
  hash.each do |key, value|
    if mapping = self.mappings[key]
      entity.instance_variable_set(:"@#{mapping.entity_field}", to_attribute(hash, value, mapping)) if mapping.set_field?
    end
  end
  entity
end

#to_hash(entity, *args) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
# File 'lib/sequel_dm/mapper.rb', line 29

def to_hash(entity, *args)
  hash = {}

  entity_mappings = self.mappings
  entity_mappings.each do |column, mapping|
    value = to_column(entity, mapping, *args)
    hash[column] = value if mapping.set_column?
  end

  hash
end