Ruby gem for building arbitrary static websites. https://rubygems.org/gems/petrify
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.3 KiB

  1. require 'haml'
  2. require 'csv'
  3. require 'logger'
  4. require "petrify/version"
  5. module Petrify
  6. @@output_dir = '_site'
  7. @@working_dir = File.join(Dir.pwd, @@output_dir)
  8. @@views_dir = 'views'
  9. @@layout_fn = File.join(@@views_dir, 'layout.haml')
  10. # https://stackoverflow.com/questions/917566/ruby-share-logger-instance-among-module-classes#6768164
  11. @@log = Logger.new($stdout)
  12. @@log.level = Logger::INFO
  13. # Write an HTML page using a specified template and optional data
  14. def self.page(path_items, template, locals = {})
  15. dir = create_path(path_items)
  16. fn = File.join(dir, 'index.html')
  17. # https://stackoverflow.com/questions/6125265/using-layouts-in-haml-files-independently-of-rails
  18. html = Haml::Engine.new(File.read(@@layout_fn)).render(Object.new, locals) do
  19. Haml::Engine.new(File.read(File.join(@@views_dir, "#{template}.haml"))).render(Object.new, locals)
  20. end
  21. File.write(fn, html)
  22. @@log.info fn
  23. # TODO - add page to sitemap.xml or sitemap.txt
  24. # https://support.google.com/webmasters/answer/183668?hl=en&ref_topic=4581190
  25. end
  26. # Write a CSV file from an array of hashes (or an empty array)
  27. def self.csv(path_items, filename, data)
  28. dir = create_path(path_items)
  29. fn = File.join(dir, filename + '.csv')
  30. if data.size > 0
  31. csv_string = CSV.generate do |csv|
  32. csv << data.first.keys # header row
  33. data.each { |row| csv << row.values }
  34. end
  35. else
  36. # There's no data so write an empty file (no header row either)
  37. csv_string = ''
  38. end
  39. File.write(fn, csv_string)
  40. @@log.info fn
  41. end
  42. # Write an arbitrary file to output (eg a JSON file)
  43. def self.file(path_items, filename, data)
  44. dir = create_path(path_items)
  45. fn = File.join(dir, filename)
  46. File.write(fn, data)
  47. @@log.info fn
  48. end
  49. def self.setup
  50. # Recursively delete working directory to ensure no redundant files are left behind from previous builds.
  51. # But preserve dot-files (especially .git directory)
  52. FileUtils.rm_r(Dir.glob(File.join(@@working_dir, '*')))
  53. Dir.mkdir(@@working_dir) unless File.directory?(@@working_dir)
  54. # Copy `public` dir to output dir
  55. FileUtils.copy_entry('public', @@working_dir)
  56. end
  57. def self.create_path(path_items)
  58. dir = File.join(@@output_dir, path_items)
  59. FileUtils.mkdir_p(dir)
  60. @@log.debug dir
  61. dir
  62. end
  63. end