Sha256: cfd2912770c2a5b4c7a784fc3d7188d390bcc34813e271751f69a380306247aa

Contents?: true

Size: 1.81 KB

Versions: 1

Compression:

Stored size: 1.81 KB

Contents

class GhostWriter::Document
  attr_reader :title, :description, :location, :url_example, :param_example, :status_example, :response_example, :output, :relative_path

  def initialize(output, attrs)
    extend(GhostWriter::Format::Markdown)
    @output           = output
    @relative_path    = Pathname.new(output).relative_path_from(GhostWriter.output_path)
    @title            = attrs[:title]
    @description      = attrs[:description]
    @location         = attrs[:location]
    @url_example      = attrs[:url_example]
    @param_example    = attrs[:param_example]
    @status_example   = attrs[:status_example]
    @response_example = attrs[:response_example]
  end

  def write_file
    unless File.exist?(File.dirname(output))
      FileUtils.mkdir_p(File.dirname(output))
    end
    doc = File.open(output, "w")

    doc.write paragraph(<<EOP)
#{headword(title, 1)}
EOP

    doc.write paragraph(<<EOP)
#{headword("access path:", 2)}
#{quote(url_example)}
EOP

    doc.write paragraph(<<EOP)
#{headword("request params:", 2)}
#{quote(param_example.inspect, :ruby)}
EOP

    doc.write paragraph(<<EOP)
#{headword("status code:", 2)}
#{quote(status_example)}
EOP

    doc.write paragraph(<<EOP)
#{headword("response:", 2)}
#{quote_response(response_example)}
EOP

    doc.write paragraph(<<EOP)
"Generated by \"#{description}\" at #{location}"
EOP

    doc.close
  end

  private
  def quote_response(body)
    if param_example[:format] && param_example[:format].to_sym == :json
      quote(arrange_json(response_example), :javascript)
    else
      quote(response_example, param_example[:format])
    end
  end

  def arrange_json(body)
    data = ActiveSupport::JSON.decode(body)
    if data.is_a?(Array) || data.is_a?(Hash)
      JSON.pretty_generate(data)
    else
      data
    end
  rescue MultiJson::DecodeError
    body
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ghost_writer-0.1.1 lib/ghost_writer/document.rb