jcraigk/story_key

View on GitHub
rakelib/lexicon.rake

Summary

Maintainability
Test Coverage
# frozen_string_literal: true
require_relative '../lib/story_key'

def noun_entries
  { countable: [], uncountable: [] }.tap do |data|
    Dir.glob('lexicons/nouns/**/*.txt') do |path|
      group = path.split('/')[-2] == 'countable' ? :countable : :uncountable
      data[group] += txtfile_lines(path)
    end
    data.each { |group, entries| data[group] = entries.sort }
  end
end

def verb_entries
  { entries: txtfile_lines('lexicons/verbs/entries.txt') }
end

def adjective_entries
  entries = []
  Dir.glob('lexicons/adjectives/*.txt') do |path|
    entries += txtfile_lines(path)
  end
  { entries: entries.sort }
end

def txtfile_lines(path)
  File.readlines(path)
      .map(&:strip)
      .reject { |l| l.start_with?('#') || l.blank? }
end

namespace :lexicon do
  desc 'Build lib/story_key/data.rb from text files'
  task :build do
    output_file = 'lib/story_key/data.rb'
    str =
      <<~TEXT
        # frozen_string_literal: true

        # This was auto-generated by `rake lexicon:build` at #{Time.current}
        # from text files stored in /lexicons

        module StoryKey::Data
          ENTRIES = {
      TEXT
    str += [].tap do |ary|
      StoryKey::GRAMMAR.values.flatten.uniq.each do |part_of_speech|
        substr = "    #{part_of_speech}: {\n"
        substr +=
          [].tap do |ary2|
            send("#{part_of_speech}_entries").each do |group, entries|
              elements = entries.map { |e| "'#{e}'" }.join(', ')
              ary2 << "      #{group}: [#{elements}]"
            end
          end.join(",\n")
        ary << "#{substr}\n    }"
      end
    end.join(",\n")
    str +=
      <<~TEXT

          }.freeze
        end
      TEXT
    File.write(output_file, str)
    puts "#{output_file} written"
  end
end