muramurasan/debride2okuribito

View on GitHub
lib/debride2okuribito.rb

Summary

Maintainability
A
35 mins
Test Coverage
require "debride"
require "debride2okuribito/version"
require "yaml"


module DebrideToOkuribito
  class Converter
    FILE_NAME = "okuribito.yml".freeze
    HEADING =
      ["# This configuration was generated by",
       "# `debride2okuribito %s`",
       "# on #{Time.now} using debride2okuribito version #{DebrideToOkuribito::VERSION}.",
       ""]
      .join("\n").freeze

    def initialize(argv)
      @argv = argv.clone.freeze
    end

    def convert_yaml
      hash = read_debride
      write_yaml(hash)
    end

    def read_debride
      puts "--- Run debride and convert to yaml..."
      debride = Debride.run(@argv.dup)
      debride_to_hash(debride)
    end

    def write_yaml(hash)
      yaml = YAML.dump(hash)

      # Workaround...
      yaml.gsub!(/^---\n/, "")
      yaml.gsub!(/^- /, "  - ")

      generate_file(yaml, FILE_NAME)
      puts "--- 'okuribito.yml' has been generated."
    end

    private

    def debride_to_hash(debride)
      hash = {}
      debride.missing.each do |klass, methods|
        ary = []
        methods.each do |method|
          if debride.method_locations["#{klass}##{method}"]
            ary << "##{method}"
          elsif debride.method_locations["#{klass}::#{method}"]
            ary << ".#{method}"
          end
        end
        hash.store(klass, ary) unless ary.empty?
      end
      hash
    end

    def generate_file(obj, filename)
      f = File.open(filename, "w")
      f.write(HEADING % @argv.join(" "))
      f.write(obj)
      f.close
    end
  end
end