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.

71 lines
2.1 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
  27. def self.csv(path_items, filename, data)
  28. dir = create_path(path_items)
  29. fn = File.join(dir, filename + '.csv')
  30. csv_string = CSV.generate do |csv|
  31. csv << data.first.keys # header row
  32. data.each { |row| csv << row.values }
  33. end
  34. File.write(fn, csv_string)
  35. @@log.info fn
  36. end
  37. # Write an arbitrary file to output (eg a JSON file)
  38. def self.file(path_items, filename, data)
  39. dir = create_path(path_items)
  40. fn = File.join(dir, filename)
  41. File.write(fn, data)
  42. @@log.info fn
  43. end
  44. def self.setup
  45. # Recursively delete working directory to ensure no redundant files are left behind from previous builds.
  46. # But preserve dot-files (especially .git directory)
  47. FileUtils.rm_r(Dir.glob(File.join(@@working_dir, '*')))
  48. Dir.mkdir(@@working_dir) unless File.directory?(@@working_dir)
  49. # Copy `public` dir to output dir
  50. FileUtils.copy_entry('public', @@working_dir)
  51. end
  52. def self.create_path(path_items)
  53. dir = File.join(@@output_dir, path_items)
  54. FileUtils.mkdir_p(dir)
  55. @@log.debug dir
  56. dir
  57. end
  58. end