DRY up csv/xls rendering, put it into model

This commit is contained in:
Devin Howard 2016-02-13 12:53:07 +08:00
parent 987d68198c
commit 4e90e4808d
3 changed files with 44 additions and 80 deletions

View file

@ -46,7 +46,6 @@ class MapsController < ApplicationController
# GET maps/:id
def show
@current = current_user
@map = Map.find(params[:id]).authorize_to_show(@current)

View file

@ -79,31 +79,30 @@ class Map < ActiveRecord::Base
json
end
def to_csv(options = {})
CSV.generate(options) do |csv|
csv << ["topics"]
csv << ["id", "name", "metacode", "x", "y", "desc", "link", "user.name", "permission"]
def to_spreadsheet
spreadsheet = []
spreadsheet << ["Topics"]
spreadsheet << ["Id", "Name", "Metacode", "X", "Y", "Description", "Link", "User", "Permission"]
self.topicmappings.each do |mapping|
topic = mapping.mappable
next if topic.nil?
csv << [
spreadsheet << [
topic.id,
topic.name,
topic.metacode.name,
mapping.x,
mapping.y,
mapping.xloc,
mapping.yloc,
topic.desc,
topic.link,
topic.user.name,
topic.permission,
topic.synapses_csv("text")
topic.permission
]
end
csv << []
csv << ["synapses"]
csv << ["id", "description", "category", "topic1", "topic2", "username", "permission"]
spreadsheet << []
spreadsheet << ["Synapses"]
spreadsheet << ["Id", "Description", "Category", "Topic1", "Topic2", "User", "Permission"]
self.synapses.each do |synapse|
csv << [
spreadsheet << [
synapse.id,
synapse.desc,
synapse.category,
@ -113,6 +112,14 @@ class Map < ActiveRecord::Base
synapse.permission
]
end
spreadsheet
end
def to_csv(options = {})
CSV.generate(options) do |csv|
to_spreadsheet.each do |line|
csv << line
end
end
end

View file

@ -1,51 +1,9 @@
<table>
<tr><th>Topics</th></tr>
<% @map.to_spreadsheet.each do |line| %>
<tr>
<th>ID</th>
<th>Name</th>
<th>Metacode</th>
<th>X</th>
<th>Y</th>
<th>Description</th>
<th>Link</th>
<th>Username</th>
<th>Permission</th>
</tr>
<% @map.topicmappings.each do |mapping| %>
<% topic = mapping.mappable %>
<% next if topic.nil? %>
<tr>
<td><%= topic.id %></td>
<td><%= topic.name %></td>
<td><%= topic.metacode.name %></td>
<td><%= mapping.xloc %></td>
<td><%= mapping.yloc %></td>
<td><%= topic.desc %></td>
<td><%= topic.link %></td>
<td><%= topic.user.name %></td>
<td><%= topic.permission %></td>
</tr>
<% line.each do |field| %>
<td><%= field %></td>
<% end %>
<tr></tr>
<tr><th>Synapses</th></tr>
<tr>
<th>ID</th>
<th>Description</th>
<th>Category</th>
<th>Topic1</th>
<th>Topic2</th>
<th>Username</th>
<th>Permission</th>
</tr>
<% @map.synapses.each do |synapse| %>
<tr>
<td><%= synapse.id %></td>
<td><%= synapse.desc %></td>
<td><%= synapse.category %></td>
<td><%= synapse.node1_id %></td>
<td><%= synapse.node2_id %></td>
<td><%= synapse.user.name %></td>
<td><%= synapse.permission %></td>
</tr>
<% end %>
</table>