Skip to content

Instantly share code, notes, and snippets.

@tillsc
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tillsc/a80cfe4abbaaa163d1a6 to your computer and use it in GitHub Desktop.
Save tillsc/a80cfe4abbaaa163d1a6 to your computer and use it in GitHub Desktop.
to_xlsx for DataMapper
# -*- encoding : utf-8 -*-
module DataMapper
module Xlsx
module Model
def xlsx_columns
self.properties.reject{ |p| p.options[:no_export] }.
sort{ |a, b| (a.options[:export_pos] || 0) <=> (b.options[:export_pos] || 0) }.
map(&:name)
end
def xlsx_human_attribute_name(field)
if (field.to_s =~ /^([^\.]+)\.(.*)$/) && relationships[$1]
"#{relationships[$1].target_model.model_name.human} - #{relationships[$1].target_model.xlsx_human_attribute_name($2)}"
else
human_attribute_name(field)
end
end
DataMapper::Property.accept_options(:no_export, :export_pos)
# Defaults
DataMapper::Property::Serial.no_export(true)
DataMapper::Property::Discriminator.no_export(true)
DataMapper::Model.append_extensions(self)
end
module Collection
def to_xlsx(options = {})
row_style = options.delete(:style) || {:sz => 12, :border => { :style => :thin, :color => "00" }}
header_style = options.delete(:header_style) || row_style.is_a?(Hash) ? row_style.merge(:alignment => {:horizontal => :center}, :b => true) : row_style
types = Array(options.delete(:types))
columns = options.delete(:columns) || self.model.xlsx_columns
p = options.delete(:package) || Axlsx::Package.new
row_style = p.workbook.styles.add_style(row_style) if row_style.is_a?(Hash)
header_style = p.workbook.styles.add_style(header_style) if header_style.is_a?(Hash)
sheet_name = options.delete(:name) || self.model.model_name.human(:count => 2)
wb = p.workbook
wb.add_worksheet(:name => sheet_name) do |sheet|
sheet.add_row columns.map{ |c| self.model.xlsx_human_attribute_name(c) }, :style => header_style
self.each do |obj|
sheet.add_row(columns.map { |c|
o = obj
field = c.to_s
while (field =~ /^([^\.]+)\.(.*)$/) && model.relationships[$1]
o = o.send($1)
field = $2
end
o.send(field)
}, :style => row_style, :types => types)
end
end
p
end
DataMapper::Collection.send(:include, self)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment