gen.rb 1.5 KB

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