Class: DomainMapper::Map

Inherits:
Object
  • Object
show all
Defined in:
lib/domain_mapper.rb

Instance Method Summary collapse

Constructor Details

#initialize(object_class, &block) ⇒ Map

Returns a new instance of Map.



5
6
7
8
9
# File 'lib/domain_mapper.rb', line 5

def initialize(object_class, &block)
  @object_class = object_class
  @rules = []
  instance_eval &block
end

Instance Method Details

#attribute(attribute_name, hash_key) ⇒ Object



11
12
13
# File 'lib/domain_mapper.rb', line 11

def attribute(attribute_name, hash_key)
  @rules << [attribute_name, hash_key]
end

#build_object(data_hash) ⇒ Object



15
16
17
18
19
20
21
22
23
# File 'lib/domain_mapper.rb', line 15

def build_object(data_hash)
  object = @object_class.new
  @rules.each do |attribute_name, hash_key|
    instance_variable_name = instance_variable_symbol(attribute_name)
    value = data_hash[hash_key]
    object.instance_variable_set(instance_variable_name, value)
  end
  object
end

#instance_variable_symbol(name) ⇒ Object



35
36
37
# File 'lib/domain_mapper.rb', line 35

def instance_variable_symbol(name)
  "@#{name}".to_sym
end

#serialize(object) ⇒ Object



25
26
27
28
29
30
31
32
33
# File 'lib/domain_mapper.rb', line 25

def serialize(object)
  fields = []
  @rules.each do |attribute_name, hash_key|
    instance_variable_name = instance_variable_symbol(attribute_name)
    value = object.instance_variable_get(instance_variable_name)
    fields << [hash_key, value]
  end
  Hash[fields]
end