class Padrino::Apidoc::Parser

Attributes

docs[R]

Public Class Methods

new() click to toggle source
# File lib/padrino/apidoc/parser.rb, line 19
def initialize
  @docs = []
  @section = 'General'
end
parse(files) click to toggle source
# File lib/padrino/apidoc/parser.rb, line 10
def parse(files)
  parser = self.new
  files.each { |file| parser.parse_file(file) }
  parser
end

Public Instance Methods

parse_file(file) click to toggle source
# File lib/padrino/apidoc/parser.rb, line 24
def parse_file(file)
  File.read(file).split("\n").each do |line|
    case line.strip
    when /\A##\s*(.+)\Z/ then
      clear_comments
      parse_section($1)
    when /\A#(\s*.*)\Z/ then
      parse_comment($1)
    when /\A(get|post|put|delete)\s+(:.+),\s+map:\s+["'](.+)["']/ then
      parse_method($1, $3)
    when /\A(get|post|put|delete)\s+["'](.+)["']/ then
      parse_method($1, $2)
    when '' then
    else
      clear_comments
    end
  end
end

Private Instance Methods

clear_comments() click to toggle source
# File lib/padrino/apidoc/parser.rb, line 46
def clear_comments
  @comments = []
end
parse_comment(comment) click to toggle source
# File lib/padrino/apidoc/parser.rb, line 54
def parse_comment(comment)
  @comments << comment
end
parse_comments(comments) click to toggle source
# File lib/padrino/apidoc/parser.rb, line 58
def parse_comments(comments)
  key = :description

  comments.inject({}) do |parsed, comment|
    case comment
      when /\A\s*@param\s+(.+?)\s+(.+)/ then
        parsed[:params] ||= []
        required = $1[0..0] == '<'
        name = $1[1..-2]
        parsed[:params] << { :name => name, :description => $2, :required => required }
      when /\A\s*@(\w+)\s*(.*)\Z/ then
        key = $1.to_sym
        parsed[key] ||= []
        parsed[key]  << $2 if $2
      else
        parsed[key] ||= []
        parsed[key]  << comment
    end
    parsed
  end.inject({}) do |flattened, (k, v)|
    case v.first
      when String then
        flattened[k] = strip_left(v.reject { |l| l.strip == "" }.join("\n"))
      else
        flattened[k] = v
    end
    flattened
  end
end
parse_method(verb, uri) click to toggle source
# File lib/padrino/apidoc/parser.rb, line 88
def parse_method(verb, uri)
  @docs << {
    :section => @section,
    :verb => verb,
    :uri  => uri,
  }.merge(parse_comments(@comments))

  clear_comments
end
parse_section(section) click to toggle source
# File lib/padrino/apidoc/parser.rb, line 50
def parse_section(section)
  @section = section.gsub("#", "").strip
end
strip_left(code) click to toggle source
# File lib/padrino/apidoc/parser.rb, line 98
def strip_left(code)
  first_line = code.split("\n").first
  num_spaces = first_line.match(/\A */)[0].length
  code.split("\n").map do |line|
    line[num_spaces..-1]
  end.join("\n")
end