gen.rb 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. require 'erb'
  2. require 'yaml'
  3. require 'optparse'
  4. require 'fileutils'
  5. def symbolize_keys(val)
  6. if val.is_a?(Hash)
  7. val.map{|k,v|
  8. [k.to_sym, symbolize_keys(v)]
  9. }.to_h
  10. elsif val.is_a?(Array)
  11. val = val.map{|v| symbolize_keys(v)}
  12. else
  13. val
  14. end
  15. end
  16. def load_locales(dir)
  17. locales = {}
  18. Dir.entries(dir).each do |ent|
  19. if ent =~ /^\w\w.yml$/
  20. lang = File.basename(ent, ".yml")
  21. yml = YAML.load_file(File.join(dir, ent))
  22. if yml
  23. locales[lang.to_sym] = symbolize_keys(yml)
  24. else
  25. locales[lang.to_sym] = {}
  26. end
  27. end
  28. end
  29. locales
  30. end
  31. def copy(indir, outdir)
  32. files = Dir.entries(indir).to_a.map{|ent|
  33. File.join(indir, ent)
  34. }.select{|ent|
  35. File.file?(ent)
  36. }
  37. FileUtils.copy(files, outdir, preserve: true)
  38. end
  39. DIR = File.dirname(__FILE__)
  40. DEFAULT_LANG = :en
  41. LANG_DIR = File.join(DIR, "locales")
  42. OUTPUT_DIR = File.join(DIR, "..", "assets")
  43. DONT_MAKE_CHANGE = "This file was automatically generated by webgen/gen.rb. Do not make changes to this file manually."
  44. locales = load_locales(LANG_DIR)
  45. template = File.read(File.join(DIR, "templates", "index.html.erb"))
  46. erb = ERB.new(template)
  47. locales.each do |lang, locale|
  48. output_path = File.join(OUTPUT_DIR, lang == DEFAULT_LANG ? "index.html" : "index.#{lang}.html")
  49. t = locales[DEFAULT_LANG].merge(locale)
  50. t[:dont_make_change] = DONT_MAKE_CHANGE
  51. t[:lang] = lang.to_s
  52. File.write(output_path, erb.result(binding))
  53. end
  54. copy(File.join(DIR, "assets"), OUTPUT_DIR)