|
| 1 | +require 'rspec_api_documentation/writers/formatter' |
| 2 | + |
| 3 | +module RspecApiDocumentation |
| 4 | + module Writers |
| 5 | + class AppendJsonWriter < JsonWriter |
| 6 | + def write |
| 7 | + index_file = docs_dir.join("index.json") |
| 8 | + if File.exists?(index_file) && (output = File.read(index_file)).length >= 2 |
| 9 | + existing_index_hash = JSON.parse(output) |
| 10 | + end |
| 11 | + File.open(index_file, "w+") do |f| |
| 12 | + f.write Formatter.to_json(AppendJsonIndex.new(index, configuration, existing_index_hash)) |
| 13 | + end |
| 14 | + write_examples |
| 15 | + end |
| 16 | + |
| 17 | + def self.clear_docs(docs_dir) |
| 18 | + nil #noop |
| 19 | + end |
| 20 | + end |
| 21 | + |
| 22 | + class AppendJsonIndex < JsonIndex |
| 23 | + def initialize(index, configuration, existing_index_hash = nil) |
| 24 | + @index = index |
| 25 | + @configuration = configuration |
| 26 | + @existing_index_hash = clean_index_hash(existing_index_hash) |
| 27 | + end |
| 28 | + |
| 29 | + def as_json(opts = nil) |
| 30 | + sections.inject(@existing_index_hash) do |h, section| |
| 31 | + h[:resources].push(section_hash(section)) |
| 32 | + h |
| 33 | + end |
| 34 | + end |
| 35 | + |
| 36 | + def clean_index_hash(existing_index_hash) |
| 37 | + unless existing_index_hash.is_a?(Hash) && existing_index_hash["resources"].is_a?(Array) #check format |
| 38 | + existing_index_hash = {:resources => []} |
| 39 | + end |
| 40 | + existing_index_hash = existing_index_hash.deep_symbolize_keys |
| 41 | + existing_index_hash[:resources].map!(&:deep_symbolize_keys).reject! do |resource| |
| 42 | + resource_names = sections.map{|s| s[:resource_name]} |
| 43 | + resource_names.include? resource[:name] |
| 44 | + end |
| 45 | + existing_index_hash |
| 46 | + end |
| 47 | + end |
| 48 | + end |
| 49 | +end |
0 commit comments