discourse/lib/export/json_encoder.rb

71 lines
1.6 KiB
Ruby
Raw Normal View History

require_dependency 'directory_helper'
2013-02-05 14:16:51 -05:00
module Export
class SchemaArgumentsError < RuntimeError; end
class JsonEncoder
attr_accessor :stream_creator
include DirectoryHelper
2013-02-05 14:16:51 -05:00
def initialize(stream_creator = nil)
@stream_creator = stream_creator
@stream_creator ||= lambda do |filename|
File.new(filename, 'w+b' )
end
@schema_data = {
schema: {}
}
@table_info = {}
2013-02-05 14:16:51 -05:00
end
def write_json(name, data)
filename = File.join( tmp_directory('export'), "#{name}.json")
filenames << filename
stream = stream_creator.call(filename)
Oj.to_stream(stream, data, :mode => :compat)
stream.close
2013-02-05 14:16:51 -05:00
end
def write_schema_info(args)
raise SchemaArgumentsError unless args[:source].present? && args[:version].present?
2013-02-05 14:16:51 -05:00
@schema_data[:schema][:source] = args[:source]
@schema_data[:schema][:version] = args[:version]
2013-02-05 14:16:51 -05:00
end
def write_table(table_name, columns)
rows ||= []
2013-02-05 14:16:51 -05:00
while true
current_rows = yield(rows.count)
break unless current_rows && current_rows.size > 0
rows.concat current_rows
end
2013-02-05 14:16:51 -05:00
# TODO still way too big a chunk, needs to be split up
write_json(table_name, rows)
2013-02-05 14:16:51 -05:00
@table_info[table_name] ||= {
fields: columns.map(&:name),
row_count: rows.size
}
2013-02-05 14:16:51 -05:00
end
def finish
@schema_data[:schema][:table_count] = @table_info.keys.count
write_json("schema", @schema_data.merge(@table_info))
2013-02-05 14:16:51 -05:00
end
def filenames
@filenames ||= []
end
end
2013-04-26 21:45:53 -04:00
end