Skip to content

Commit

Permalink
Exporter added and rake task to generate the files
Browse files Browse the repository at this point in the history
  • Loading branch information
iagirre committed Dec 7, 2017
1 parent 946c9ce commit e1d675b
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
65 changes: 65 additions & 0 deletions lib/events_exporter.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
class EventsExporter
FIELDS = ['title', 'description', 'scheduled', 'user_id', 'position_id', 'location', 'status',
'notes', 'reasons', 'published_at', 'canceled_at',
'organization_name', 'lobby_scheduled', 'general_remarks', 'lobby_contact_firstname',
'lobby_contact_lastname', 'lobby_contact_email', 'lobby_contact_phone', 'manager_general_remarks'].freeze

def headers
FIELDS.map { |f| I18n.t("events_exporter.#{f}") }
end

def event_to_row(event)
FIELDS.map do |f|
event.send(f)
end
end

def windows_headers
windows_array headers
end

def windows_event_row(event)
windows_array event_to_row(event)
end

def save_csv(path)
CSV.open(path, 'w', col_sep: ';', force_quotes: true, encoding: "ISO-8859-1") do |csv|
csv << windows_headers
Event.with_lobby_activity_active.find_each do |event|
csv << windows_event_row(event)
end
end
end

def save_xls(path)
book = Spreadsheet::Workbook.new
sheet = book.create_worksheet
sheet.row(0).default_format = Spreadsheet::Format.new color: :blue, weight: :bold
sheet.row(0).concat headers
index = 1
Event.with_lobby_activity_active.find_each do |event|
sheet.row(index).concat windows_event_row(event)
index += 1
end

book.write(path)
end

def save_json(path)
data = []
h = headers
Event.with_lobby_activity_active.find_each do |event|
data << h.zip(windows_event_row(event)).to_h
end
File.open(path, "w") do |f|
f.write(data.to_json)
end
end

private

def windows_array(values)
values.map { |v| v.to_s.encode("ISO-8859-1", invalid: :replace, undef: :replace, replace: '') }
end

end
14 changes: 14 additions & 0 deletions lib/tasks/export.rake
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,18 @@ namespace :export do
exporter.save_json(folder.join('public_organizations.json'))
end

desc "Exports organizations' events to public/export/organizations_events.csv,
public/export/organizations_events.xls and public/export/organizations_events.json"
task events: :environment do
folder = Rails.root.join('public', 'export')
FileUtils.rm_rf folder
FileUtils.mkdir_p folder

exporter = EventsExporter.new

exporter.save_csv(folder.join('organizations_events.csv'))
exporter.save_xls(folder.join('organizations_events.xls'))
exporter.save_json(folder.join('organizations_events.json'))
end

end

0 comments on commit e1d675b

Please sign in to comment.