class Hanami::Annotate::CLI::Generate

Generate annotation for Hanami entities and repositories

usage:

$ bundle exec hanami annotate

@todo add support for mysql and sqlite3 etc..

Public Instance Methods

call(*) click to toggle source
# File lib/hanami/annotate/cli/generate.rb, line 14
def call(*)
  postgres
  @tables.each do |table|
    table_info = \
      `ruby -e "print %q{\\d #{table}}" | bundle exec hanami db console`

    comment = commentize(table_info)

    files = entity_and_repository_path(table)
    remove_head_comments(files)
    adds_comments(files, comment)
  end
end

Private Instance Methods

adds_comments(files, comment) click to toggle source
# File lib/hanami/annotate/cli/generate.rb, line 43
def adds_comments(files, comment)
  files.each do |file|
    content = ''
    File.open(file) { |f| content += f.read }
    File.open(file, 'w') { |f| f.puts(comment + content) }
  end
end
commentize(str) click to toggle source
# File lib/hanami/annotate/cli/generate.rb, line 51
def commentize(str)
  str.each_line.map do |line|
    line.insert(0, '# ')
  end.join
end
entity_and_repository_path(table) click to toggle source
# File lib/hanami/annotate/cli/generate.rb, line 38
def entity_and_repository_path(table)
  Dir[Hanami.root.join('lib', '*', '{entities,repositories}', '*')]
    .grep(Regexp.new(Dry::Inflector.new.singularize(table)))
end
non_comment_line_number(lines) click to toggle source
# File lib/hanami/annotate/cli/generate.rb, line 72
def non_comment_line_number(lines)
  lines.index do |line|
    line.strip[0] != '#'
  end
end
postgres() click to toggle source
# File lib/hanami/annotate/cli/generate.rb, line 30
def postgres
  output = `ruby -e "print '\\dt'" | bundle exec hanami db console`
  lines = output.each_line.grep(/\A.*public(?!.*schema_migrations)/)
  @tables = lines.map do |line|
    line.split('|')[1].strip
  end
end
remove_head_comments(files) click to toggle source
# File lib/hanami/annotate/cli/generate.rb, line 57
def remove_head_comments(files)
  files.each do |file|
    comment_removed_content = ''
    File.open(file) do |f|
      raw_content = f.read

      lines = raw_content.each_line.to_a
      index = non_comment_line_number(lines)
      comment_removed_content = lines[index..-1].join
    end

    File.open(file, 'w') { |f| f.puts(comment_removed_content) }
  end
end