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.

61 regels
1.8 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. def self.page(path_items, template, locals = {})
  14. dir = create_path(path_items)
  15. fn = File.join(dir, 'index.html')
  16. # https://stackoverflow.com/questions/6125265/using-layouts-in-haml-files-independently-of-rails
  17. html = Haml::Engine.new(File.read(@@layout_fn)).render(Object.new, locals) do
  18. Haml::Engine.new(File.read(File.join(@@views_dir, "#{template}.haml"))).render(Object.new, locals)
  19. end
  20. File.write(fn, html)
  21. @@log.info fn
  22. # TODO - add page to sitemap.xml or sitemap.txt
  23. # https://support.google.com/webmasters/answer/183668?hl=en&ref_topic=4581190
  24. end
  25. def self.csv(path_items, filename, data)
  26. dir = create_path(path_items)
  27. fn = File.join(dir, filename + '.csv')
  28. csv_string = CSV.generate do |csv|
  29. csv << data.first.keys # header row
  30. data.each { |row| csv << row.values }
  31. end
  32. File.write(fn, csv_string)
  33. @@log.info fn
  34. end
  35. def self.setup
  36. # Recursively delete working directory to ensure no redundant files are left behind from previous builds.
  37. # But preserve dot-files (especially .git directory)
  38. FileUtils.rm_r(Dir.glob(File.join(@@working_dir, '*')))
  39. Dir.mkdir(@@working_dir) unless File.directory?(@@working_dir)
  40. # Copy `public` dir to output dir
  41. FileUtils.copy_entry('public', @@working_dir)
  42. end
  43. def self.create_path(path_items)
  44. dir = File.join(@@output_dir, path_items)
  45. FileUtils.mkdir_p(dir)
  46. @@log.debug dir
  47. dir
  48. end
  49. end