Method: Marty::DataExporter.export_attrs

Defined in:
lib/marty/data_exporter.rb

.export_attrs(klass, obj, attrs = nil, exclude_attrs = []) ⇒ Object



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/marty/data_exporter.rb', line 92

def self.export_attrs(klass, obj, attrs = nil, exclude_attrs = [])
  col_types = Marty::DataConversion.col_types(klass)

  attr_list_raw = (attrs || col_types.keys).map(&:to_s) - exclude_attrs
  attr_list = get_attrs_in_order(klass, attr_list_raw)

  attr_list.map do |c|
    v = obj.send(c.to_sym)
    type = col_types[c]

    # return [value] if not assoc or nil
    next [v] if !type.is_a?(Hash)

    # no child row, return nils for each field
    next [nil] * type[:assoc_keys].count if v.nil?

    assoc_keys  = type[:assoc_keys]
    assoc_class = type[:assoc_class]
    assoc_obj   = assoc_class.find(v)

    # FIXME: this recursion will fail if a reference which then
    # makes sub-references is nil.  To handle this, we'd need to
    # create the export structure first.
    export_attrs(assoc_class, assoc_obj, assoc_keys).flatten(1)
  end
end