Class: ReeDto::BuildDto

Inherits:
Object
  • Object
show all
Includes:
Ree::FnDSL
Defined in:
lib/ree_lib/packages/ree_dto/package/ree_dto/functions/build_dto.rb

Instance Method Summary collapse

Instance Method Details

#call(&proc) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/ree_lib/packages/ree_dto/package/ree_dto/functions/build_dto.rb', line 17

def call(&proc)
  klass = get_caller
  klass.include DtoInstanceMethods
  klass.extend DtoClassMethods

  builder = DtoBuilder.new(self)
  builder.instance_exec(&proc)

  klass.send(:set_fields, builder.fields)
  klass.send(:set_collections, builder.collections)

  builder.fields.each do |field|
    klass.instance_exec do
      contract None => field.contract
    end

    klass.define_method field.name do
      get_value(field.name)
    end

    if field.setter
      klass.instance_exec do
        contract field.contract => field.contract
      end

      klass.define_method :"#{field.name}=" do |val|
        set_value(field.name, val)
      end
    end
  end

  builder.collections.each do |collection|
    col_class = build_dto_collection_class(klass, collection.name, collection.contract)
    col_class.class_exec(&collection.filter_proc) if collection.filter_proc

    klass.instance_exec do
      contract ArrayOf[collection.contract] => DtoCollection
    end

    klass.define_method "#{collection.name}=" do |list|
      col = send(collection.name)

      list.each do |item|
        col.add(item)
      end

      col
    end

    klass.instance_exec do
      contract None => DtoCollection
    end

    klass.define_method collection.name do
      @collections ||= {}

      @collections[collection.name] ||= col_class.new(
        collection.name, collection.contract, klass
      )
    end
  end

  nil
end