lib/decisive/template_handler.rb in decisive-0.2.0 vs lib/decisive/template_handler.rb in decisive-0.3.0
- old
+ new
@@ -18,46 +18,60 @@
end
end
module DSL
def csv records, filename:, &block
- Context.new([], records, filename).tap do |context|
- context.instance_eval &block
- end
+ Context.new(records, filename, block)
end
end
- class Context < Struct.new(:columns, :records, :filename)
- class Column < Struct.new(:field, :label, :block); end
-
- def column field, label: field.to_s.humanize, &block
- block ||= ->(record) { record.send(field) }
- columns << Column.new(field, label, block)
- end
-
+ class Context < Struct.new(:records, :filename, :block)
def to_csv
- rows
- .map { |rows| rows.map(&:to_s) }
- .map(&:to_csv)
- .join
+ (header + body).map(&:to_csv).join
end
private
- def rows
- [header] + body
- end
-
def header
- columns.map(&:label)
+ [keys]
end
def body
- records.map do |record|
- columns.map do |column|
- column.block.call(record)
- end
+ hashes.map do |hash|
+ hash.values_at(*keys)
end
+ end
+
+ def keys
+ @keys ||= hashes.flat_map(&:keys).uniq
+ end
+
+ def hashes
+ @hashes ||= records.map do |record|
+ Row.new(record, block).to_hash
+ end
+ end
+ end
+
+ class Row < Struct.new(:record, :block)
+ def to_hash
+ @hash = {}
+ instance_exec record, &block
+ @hash
+ end
+
+ private
+
+ def column key, value=nil, &block
+ @hash[key] = if block_given?
+ block.call(record)
+ elsif value.is_a?(Symbol)
+ record.send(value)
+ elsif value.nil?
+ record.send(key.parameterize.underscore.to_sym)
+ else
+ value
+ end.to_s
end
end
end